-1

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

osunkaya
  • 93
  • 1
  • 1
  • 9

1 Answers1

1

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

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
flutteRguy
  • 46
  • 7
  • 1
    [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => dynamic' is not a subtype of type '(String, dynamic) => MapEntry' of 'transform' – osunkaya Nov 13 '21 at 16:14
  • Thanks for sharing the error, I forgot to include the declaration of the types in the `map`. I've updated the code in my response and provided a screenshot for reference. – flutteRguy Nov 13 '21 at 17:17
  • Hi, i'm sending the json as string from response.body, but getting "Unhandled Exception: type 'String' is not a subtype of type 'Map' in type cast" tried to cast retrun value to List but extractedData should change i guess, stucked here. `static List getVacDates(String s) { final newList = jsonEncode(s); final extractedData = jsonDecode(newList) as Map; final china= extractedData['timeline'].map((e) => e["date"]); List StringList = china.cast(); print(StringList); return StringList; }` – osunkaya Nov 13 '21 at 19:51