Nested JSON
- Flutter course
- Intermediate
- Lesson 53/99
- 4 min
Access nested Maps and read inner objects.
Accessing nested JSON
JSON responses usually contain nested objects. After jsonDecode, the value of the outer Map is itself a Map. You reach inner values by chaining square brackets.
const s = '{"kullanici": {"ad": "Ela", "yas": 22}}';
final m = jsonDecode(s) as Map<String, dynamic>;
final ad = m['kullanici']['ad'] as String;
print(ad); // ElaThe inner Map is of type Map<String, dynamic> at runtime, so casting with as is safe.
Missing keys and the null risk
In nested access, reaching a missing key returns null instead of throwing. But applying another bracket on null throws a runtime error.
final m = jsonDecode('{"a": {}}') as Map<String, dynamic>;
print(m['a']['b']); // null
print(m['a']['b']['c']); // Error!So with nested access you must make sure each step exists.
Practice Print the city from nested JSON
Decode the string s with jsonDecode and print the inner 'sehir' value with print.
Starter code
import 'dart:convert';
void main() {
const s = '{"adres": {"sehir": "Bursa"}}';
// iç içe erişimle 'sehir' değerini yazdır
}Sample solution
import 'dart:convert';
void main() {
const s = '{"adres": {"sehir": "Bursa"}}';
final m = jsonDecode(s);
print(m['adres']['sehir']);
}Expected output
Bursa
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the expression m['kullanici']['ad'] return?
- The inner Map itself
- Only the outer Map
- The 'ad' value inside the inner Map Correct answer
- It returns a List
Explanation: m['kullanici'] gives the inner Map; the second ['ad'] step accesses the 'ad' value inside it. The result is the String 'Ela'.
2 Nested access
import 'dart:convert';
void main() {
const s = '{"adres": {"sehir": "Ankara"}}';
final m = jsonDecode(s);
final sehir = m['adres'][____];
print(sehir);
}
import 'dart:convert';
void main() {
const s = '{"adres": {"sehir": "Ankara"}}';
final m = jsonDecode(s);
final sehir = m['adres']['sehir'];
print(sehir);
}
Explanation: To reach the 'sehir' value inside the inner Map, the second bracket must contain 'sehir'.
3 Nested access parts
| Term | Meaning |
|---|---|
m['kullanici'] |
Accesses the inner Map |
['ad'] |
Gives the 'ad' value in the inner Map |
as String |
Casts the value to String |
jsonDecode |
Decodes the JSON string into a Map |