Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add json values in to the list of object

How I can get all the values in this JSON and add all the value in to the list of object in the dart?

 "data": [
        {
            "$id": "2",
            "serviceId": 1017,
            "name": "اکو",
            "code": "235",
            "price": 1562500,
            "isDefault": true,
            "transportCostIncluded": false,
            "qty": 0,
            "minQty": 1,
            "maxQty": 2,
            "description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
            "contractorSharePercent": 65,
            "unitMeasureId": 7,
            "unitMeasureName": "هر 60 دقیقه",
            "superContractorsId": null
        },
       
    ],

like this var list = ["2",1017,....]

like image 558
Masoud H Avatar asked Oct 28 '25 21:10

Masoud H


2 Answers

Assuming you've a JSON file, which you may have parsed like this:

String json = await rootBundle.loadString('file_name.json');
var response = jsonDecode(json);

This is how you can do it:

List<dynamic> jsonData; //similar to var jsonData = [something, something, ...]

//traversing through each value in the key value arrangement of the json
for (var k in response.values) {
   jsonData.add(k);  //adding each value to the list
}

After the loop ends, jsonData will have all the values of your JSON file.

like image 84
Shourya Shikhar Avatar answered Oct 31 '25 12:10

Shourya Shikhar


It's important for you to know that even if you put the keys on a list, they won't necessarily be in order, because of the way maps work.

Assuming your json is a map and not a json string, you could put all of the values on a list like so:

var myList = (jsonObject['data'] as List).fold<List>(
  [], 
  (prev, curr) => [...prev, ...curr.values]
);

if you were talking about a json string:

Map<String, dynamic> jsonObject = jsonDecode(jsonString);
like image 24
h8moss Avatar answered Oct 31 '25 12:10

h8moss