I’m trying to map a variable to receive data from my API through jsonDecode(response.body)
Here’s how I try to map, but I don’t know if this is correct or not.
The data from API.
{
"days": {
"region1": [
{
"1": "2",
"2": "Monday",
"3": "25",
"4": "10"
},
{
"1": "1",
"2": "Tuesday",
"3": "21",
"4": "12"
},
]
}
}
I want to have a variable to receive that data above.
final Map<String, dynamic> listData = jsonDecode(response.body);
for (final item in listData.entries) {
print(item.days);
}
How can I print out the days
? or region1
? how can I access to value Monday
I try this print(item.days)
but it not work.
2
Answers
First, to access the "days" key in your JSON data, you can directly use listData[‘days’]. You don’t need to iterate through the entries for this specific case.
Second, "days" contains a map where the keys are strings like "region1," and the values are lists of maps. You can access the "region1" data by using listData[‘days’][‘region1’].
You can refer this one:
To get the map attribute, you can use the property name inside the square bracket.
In your code, you can do the same.
Example:
Output:
But, I suggest you to convert the Map into Models and access the properties. You can convert the json data to dart model from HERE