How to update the local json field in flutter - json

I am new to flutter and dart I read a lot of web article and documentation but didn't able to figure out how to update JSON field I have a local JSON file like
{
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}]}
I want to update the filed favorite to true in JSON file Is there any way to do this

You Can parse the JSON like this
Map<String, dynamic> data = jsonDecode(jsonString);
And if you want to make each favorite true then You can use looping like this
(data["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
if you want to set a single object value true then you need to pass the position like this
(data["quotes"] as List<dynamic>)[position]['favorite'] = true;
Addition
Here is the link to encode and decode the JSON

You can use a forEach loop on the quotes list in the JSON and set favourite to true inside it. I'm assuming you have a parsed your String data into JSON using jsonDecode or json.decode.
If not, here's a link on how to parse JSON data in Dart.
Consider the below code -
Map<String, dynamic> jsonData = {
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}
]};
(jsonData["quotes"] as List<dynamic>).forEach((item) {
item["favorite"] = true;
});
You can also alternatively use shorthand syntax for the forEach loop function like below -
(jsonData["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);

first take this json array to any variable and then understand the hierarchy .
e.g "jsonArr" is the array that hold that data then ..
jsonArr['quotes'][0]['favorite'] = true;
or you can put this in a for loop and traverse this loop to the length of the json array.

You can use the following method. The field favorite is changed to true when the button is pressed.
FlatButton(
child: Text('Add Favourite'),
onPressed: (){
myJson['quotes'][myIndex]['favorite'] = true;
})

Related

I think parsing this type of json response is impossible in Dart. How can I convert this json to Dart Class?

An API gives me json response like this:
[{"version": "v3.5"}, {"setup": true}, {"address": "e7d398b"}, {"connected": true}, {"active": true}, {"id": "ce7143"}, {"genuine": true}]
As you can see, this is a list of objects. I tried parsing it like this using quicktype generated model class-
List<Result>.from(result.map((x) => Result.fromJson(x)));
But it's failing since each of the objects are of different types.
I think I have to convert each of the objects in the array one by one to Dart classes and add it to an Array.
So I tried this (I am using dio) -
final result = response.data;
var b = List.empty(growable: true);
result.map((x) => b.add(x));
But it's not working.
How can I atleast access the elements of the array?
Solved
Inspired by the accepted answer, I was able to generate corresponding Dart Class. Never thought can looping through a map is possible, IDE was not giving any clue.
final result = response.data;
Map<String, dynamic> map = {};
for (var e in result) {
map.addAll(e);
}
final finalResult = Result.fromJson(map);
return finalResult;
As Randal Schwartz mentioned above, there is no JSON you can not parse with Dart.
In your case, you have a List of Map objects. What you can do is:
final data = jsonDecode(json) as List;
Map<String, dynamic> map = {};
for (var e in data) {
map.addAll(e);
}
print(map);
//prints
{version: v3.5, setup: true, address: e7d398b, connected: true, active: true, id: ce7143, genuine: true}
If you're using the dio flutter package it returns decoded json, no
need to call for jsonDecode.
I recommend using json code generation if you face large json instead of relying on quicktype generated models.
There's no JSON that isn't parsable with Dart. But you might end up with a data structure that requires careful navigation. Classes make it easier, but there isn't always a class structure for any arbitrary JSON, and maybe that's your point. In that case, you'll have to navigate to the data of interest in an ad-hoc fashion.

How to iterate through nested dynamic JSON file in Flutter

So I have two JSON files with different fields.
{
"password": { "length": 5, "reset": true},
}
"dataSettings": {
"enabled": true,
"algorithm": { "djikstra": true },
"country": { "states": {"USA": true, "Romania": false}}
}
I want to be able to use the same code to be able to print out all the nested fields and its values in the JSON.
I tried using a [JSON to Dart converter package](https://javiercbk.github.io/json_to_dart/.
However, it seems like using this would make it so I would have to hardcode all the values, since I would retrieve it by doing
item.dataSettings.country.states.USA
which is a hardcoded method of doing it. Instead I want a way to loop through all the nested values and print it out without having to write it out myself.
You can use ´dart:convert´ to convert the JSON string into an object of type Map<String, dynamic>:
import 'dart:convert';
final jsonData = "{'someKey' : 'someValue'}";
final parsedJson = jsonDecode(jsonData);
You can then iterate over this dict like any other:
parsedJson.forEach((key, value) {
// ... Do something with the key and value
));
For your use case of listing all keys and values, a recursive implementation might be most easy to implement:
void printMapContent(Map<String, dynamic> map) {
parsedJson.forEach((key, value) {
print("Key: $key");
if (value is String) {
print("Value: $value");
} else if (value is Map<String, dynamic>) {
// Recursive call
printMapContent(value);
}
));
}
But be aware that this type of recursive JSON parsing is generally not recommendable, because it is very unstructured and prone to errors. You should know what your data structure coming from the backend looks like and parse this data into well-structured objects.
There you can also perform input validation and verify the data is reasonable.
You can read up on the topic of "JSON parsing in dart", e.g. in this blog article.

typescript - load json from url and get access to array of json objects

I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}

Node-RED parse json

I am trying to pull out the value "533"
{
"d": {
"ItemValue_1": 533
},
"ts": "2021-01-20T10:59:41.958591"
}
This does not work
var ItemValue_1 = msg.payload.ItemValue_1;
msg.payload = ItemValue_1;
return msg;
My result is unsuccessful
I was able to solve on my own, it works.
sensorMeasurement=JSON.parse(msg.payload);
msg.payload=sensorMeasurement.d;
var msgout = {payload : msg.payload.ItemValue_1}
return msgout;
The better way to do this is as follows:
Add a JSON node before the function node, this will turn a string payload in to a JSON object (assuming the string actually represents a JSON object).
Then if you are using a function node the following:
msg.payload = msg.payload.d.ItemValue_1;
return msg;
It is bad practice to create a new object as you did in your answer as it throws away any meta data that may be required later that is attached to the original object.
Rather than use a function node it would also be cleaner to use a change node and the Move mode to shift the msg.payload.d.ItemValue_1 to msg.payload

Create nested JSON structure with Coldfusion

I've been converting CF structs etc to JSON for a while now, and all good. Coldbox in particular makes this really easy.
However, I am currently working with a jQuery Datatable and need to pass it jSON in the format below.
I am starting with an array of objects.
I only want certain properties in each object to go into the final JSON String.
I'm running around in circles and possibly totally overcomplicating converting my data into this format JSON. Can anyone help, or suggest an easy way I might be able to do this..
Also worth mentioning I am building this in coldbox. Coldfusion 9.
{ "aaData": [ [ "Test1", "test#test1", "444444444", "<i class=''icon-pencil icon-large'' data-id=''s1''></i>" ],[ "Test2", "test#test2", "555555555", "<i class=''icon-pencil icon-large'' data-id=''s2''></i>" ],[ "Test3", "test#test3", "666666666", "<i class=''icon-pencil icon-large'' data-id=''s3''></i>" ] ]}
Many Thanks!
======================================================
Here is the code that game we what I needed:
var dataStruct = structNew();
var dataArray = arrayNew(1);
var subsArray = arrayNew(1);
var subs = prc.org.getSubscribers();
for (i=1; i<=arrayLen(subs); i++){
arrayAppend(subsArray,"#subs[i].getName()#");
arrayAppend(subsArray,"#subs[i].getEmail()#");
arrayAppend(subsArray,"#subs[i].getMobile()#");
arrayAppend(subsArray,"<i class='icon-pencil icon-large' data-id='s#subs[i].getID()#'></i>");
arrayAppend(dataArray,subsArray);
arrayClear(subsArray);
};
structInsert(dataStruct,'aaData',dataArray);
event.renderData('json',dataStruct);
OK, so you've got an array which has objects, and the objects contain all the properties which you need to end up in this JSONed array, yeah?
So do this:
create a new array
loop over the array of objects
create a struct
put all the values from each object you need to go into the JSON; be mindful to use associative array notation when setting the keys, to perserve the case of the keys
append the struct to the new array
/loop
serializeJson the new array
I don't think there's any simpler way of doing it.