Trouble extracting JSON data in Flutter - json

I'm trying to render a list of elements in Flutter and the list data is coming from a REST API. However, I'm having trouble understanding how to parse this data correctly. I want the parsed data to look like this:
['Chicken roll', 'Fresh salads', 'Wrape', 'Pizza', 'Fried Chicken', 'Veggie', 'Burgers']
This is the JSON object:
{
"status":true,
"error_message":"",
"success_message":"Task completed successfully.",
"data":[
{
"id":1064,
"name":"Chicken roll"
},
{
"id":1061,
"name":"Fresh salads"
},
{
"id":1059,
"name":"Wrape"
},
{
"id":1057,
"name":"Pizza"
},
{
"id":1055,
"name":"Fried chicken"
},
{
"id":1053,
"name":"Veggie"
},
{
"id":1051,
"name":"Burgers"
}
]
}
How do I achieve this? My current code is as follows:
var _categoryResponse;
var _categoryData;
var categoryData;
List<String> allCategories;
Future fetchCategories() async {
_categoryResponse = await http.get(_categories);
_categoryResponse = jsonDecode(_categoryResponse.body);
_categoryData = _categoryResponse['data'].toString();
categoryData = categoryDataFromJson(_categoryData);
}

List<String> listOfNames = [];
List<dynamic> data = json['data'] as List;
data.forEach((item) => listOfNames.add(item['name']));
print(listOfNames);
Gives the following output:
[Chicken roll, Fresh salads, Wrape, Pizza, Fried chicken, Veggie, Burgers]
I'm assuming the variable json above contains your parsed JSON object (as given in the example).
Not sure why you're converting JSON to String as its much easier to work with the dynamic map, at least when it comes to fetching particular attributes like the name of each object within the data list.
Basically, the data key maps to a list of objects with attributes id and name. Hence, you can run a forEach() on the list obtained and fetch the name for each object in it.

Related

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)
}
}

Parsing a JSON API response

An API is giving me a JSON response like so :
{
"amountCredited":0,
"isFirstOrder":false,
"orderItems":[
{
"_id":624342e1c66be9001d501230,
"status":2,
"pinCode":749326,
"kioskId":61bb3982089a66001db4ab77,
"kioskActivityId":620668ad433322b99557c874
}
]
}
I'm trying to access the data inside the "orderItems" in order to feed it to an existing parsing model in the App
order = OrderItemModel.fromJson(response.body['orderItems'] as Map<String, dynamic>);
but since the data inside orderItems JSON response is inside an array I can't access it this way..
How can I access it knowing that this JSON "orderItems" array will always only have one item as a response ?
Would something like response.body['orderItems' : [0]] enable me to access the first item data ?
Since you always know that the array will always have only one item. We'll first make it a List & then access the first element.
order = OrderItemModel.fromJson((response.body['orderItems'] as List<dynamic>).first as Map<String, dynamic>);
To understand it a bit better refer to the code below:
The JSON response contains an array, which we need to access.
final ordersArray = response.body['orderItems'] as List<dynamic>;
Then we want to access the first order (according to the question)
final firstOrder = ordersArray.first as Map<String, dynamic>;
Once we have the order, we'll convert it to the model
final order = OrderItemModel.fromJson(firstOrder);
EDIT:
as it was pointed out in a comment List objects have a getter called first which can be used to get the first element, the code has been updated with that.
You need to convert as Map and List because Flutter deal only with this datatypes. For example:
Map order1 = {
"_id":"624342e1c66be9001d501230",
"status":2,
"pinCode":749326,
"kioskId":"61bb3982089a66001db4ab77",
"kioskActivityId":"620668ad433322b99557c874"
};
Map order2 = {
"_id":"224342e1c66be9001d501232",
"status":1,
"pinCode":248023,
"kioskId":"41bb3982089a66001db4ab74",
"kioskActivityId":"720668ad433322b99557c875"
};
Map m = {
"amountCredited":0,
"isFirstOrder":false,
"orderItems":[
order1,
order2
]
};
print(m['orderItems'][1]);
print(m['orderItems'][1]['pinCode']);
The result will be:
{_id: 224342e1c66be9001d501232, status: 1, pinCode: 248023, kioskId: 41bb3982089a66001db4ab74, kioskActivityId: 720668ad433322b99557c875}
248023

How to access nested elements in json in flutter?

This is the json data structure used in flutter
flutter: {
"members": [
{
"firstName": "Michael"
},
{
"firstName": "Jennifer"
},
{
"firstName": "Lisa"
}
]
}
To access the above data I used the below code
var parsedData = json.decode(state.successResponse);
var name = parsedData['members'];
I am not able to access the inner field of firstName in the above json.
How should I do that?
Since members is JSON Array you can convert it to dart List type and then you can operate on the list (adding, removing, accessing elements by index).
You can do something like this -
List members = parsedData['members'];
//You can access members by index
print(members[1]); //prints {firstName: Jennifer}
print(members[1]['firstName']); //prints Jennifer
//Or you can iterate over the list
members.forEach((member){
print(member['firstName']);
});
Hope this helps!

How to loop and get the json object

{
"result": [
{
"id": "a258377906705d889422fd0b41c324b8",
"coordinate": {
"London": {
"x": 65.565709,
"y": 98.931235
},
"New_York": {
"x": 37.59751,
"y": 47.448718
}
}
}
]
}
If I have a json like the above one,
how can I loop to get the x,y coordinate and if i get more data to get, how can I get it?
If I want to also get the London and New York to add to an array list, how can I do it (cannot directly add the name because there are more than two data)?
You can parse it and then use it using JSON.parse( insert json here ).
Basically what it does is that it takes your JSON string and converts it into a usable JSON.
For adding new objects into another object, I recommend using Object.assign().
You can refer the details here: Link
Here is an example given from the site:
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Object.assign() takes a target object as the first parameter and modifies it with the additional parameters that we're provided.
In your case, you can update your object like this:
var countryCoord = JSON.parse(yourjsondata); // parse the json that you included
Object.assign(countryCoord, newCoord, newCoord2,...etc); //this would update countryCoord alone
Online parser: Link
You have to handle the json and understand where you are getting the JSONObject and where you are getting the JSONArray, On basis of that you can parse the JSON accordingly.
Please refer the link for more information on parsing json object with nested items in Java:
Retrieving nested arrays values with java