Solved: Flutter/Dart Get All Values Of a Key from a JSON

Question

Asked by osunkaya on November 13, 2021 (source).

How can i get all values of a second level key in a JSON?

I need to get all total values as like 409571117, 410559043, 411028977, 411287235

JSON:

{"country":"USA","timeline":

[{"total":409571117,"daily":757824,"totalPerHundred":121,"dailyPerMillion":2253,"date":"10/14/21"},

{"total":410559043,"daily":743873,"totalPerHundred":122,"dailyPerMillion":2212,"date":"10/15/21"},    

{"total":411028977,"daily":737439,"totalPerHundred":122,"dailyPerMillion":2193,"date":"10/16/21"},    

{"total":411287235,"daily":731383,"totalPerHundred":122,"dailyPerMillion":2175,"date":"10/17/21"}]}

I can able to get first level values but i don't know how to get second level.

final list = [
{'id': 1, 'name': 'flutter', 'title': 'dart'},
{'id': 35, 'name': 'flutter', 'title': 'dart'},
{'id': 93, 'name': 'flutter', 'title': 'dart'},
{'id': 82, 'name': 'flutter', 'title': 'dart'},
{'id': 28, 'name': 'flutter', 'title': 'dart'},
  ];

final idList = list.map((e) => e['id']).toList(); // [1, 35, 93, 82, 28]

python version of same question: Python: Getting all values of a specific key from json

Answer

Question answered by flutteRguy (source).

UPDATE: You must declare the types in map. See below.

Have you tried subsetting on timeline after using jsonDecode?

For example, you format the data as json:

final newList = jsonEncode( 
        { "country": "USA", "timeline":[
                { "total": 409571117, "daily": 757824, "totalPerHundred": 121, "dailyPerMillion": 2253, "date": "10/14/21" },
                {"total": 410559043, ...

Then you decode the data into the list you want by first subsetting the timeline feature:

final extractedData = jsonDecode(newList) as Map<String, dynamic>;

final newIdList = extractedData['timeline'].map((e) => e["total"]).toList();

Screenshot of list of totals from data

DART FLUTTER
SHARE: