CodeBlanks Logo Icon CodeBlanks

jsonDecode

Learn JSON parsing with jsonDecode.

jsonDecode

jsonDecode(String) comes from dart:convert and turns JSON text into a Dart object. The result is dynamic; usually cast to Map<String, dynamic> or List.

Example: var data = jsonDecode('{"name":"Ayşe","age":30}');. data['name'] yields 'Ayşe'. Malformed JSON throws FormatException.

Without a cast, data.name does not work; use data['name']. For type safety a fromJson factory is preferred (we will see it in L3).

Reading as a Map

A JSON object is cast to Map<String, dynamic>: var m = jsonDecode(s) as Map<String, dynamic>;. Then values are read via m['key'].

For nested objects, chain access: m['user']['name']. Each level is dynamic, so the compiler does not check; errors appear at runtime.

For lists, var list = jsonDecode(s) as List;. Elements are still dynamic; cast to a type.

Practice Decode JSON text and print it

Add import 'dart:convert';. Inside main add var data = jsonDecode('{"name":"Ayşe","age":30}');. Add print(data['name']);.

Starter code

main.dart
void main() {
  // add dart:convert import; decode JSON text; print name
}

Sample solution

main.dart
import 'dart:convert';

void main() {
  var data = jsonDecode('{"name":"Ayşe","age":30}');
  print(data['name']);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does jsonDecode return?

  • dynamic Correct answer
  • Map
  • String
  • int

Explanation: jsonDecode returns dynamic; cast to Map/List.

2 Decode JSON text

Question
var data = ____(jsonText);
Answer
var data = jsonDecode(jsonText);

Explanation: jsonDecode turns JSON text into a Dart object.

3 Match the jsonDecode parts

Term Meaning
jsonDecode String → dynamic
Map<String, dynamic> Object cast
data['key'] Value access
FormatException Malformed JSON

All lessons in Advanced