CodeBlanks Logo Icon CodeBlanks

jsonDecode

Parse a JSON string into a Map with jsonDecode.

Decode JSON with jsonDecode

JSON is the most common format for data coming from a server. In Dart you turn a JSON string into a Map with jsonDecode. This function lives in the dart:convert library.

import 'dart:convert';

const veri = '{"ad": "Ayşe", "yas": 28}';
final map = jsonDecode(veri);
print(map['ad']);  // Ayşe

The returned object is actually of type Map<String, dynamic>; the type of each value is determined at runtime.

Importing dart:convert

To use jsonDecode, add import 'dart:convert'; at the top of the file. This library is part of the Dart SDK; no extra package is needed.

import 'dart:convert';

void main() {
  final s = '{"sehir": "İstanbul"}';
  final m = jsonDecode(s) as Map<String, dynamic>;
  print(m['sehir']);  // İstanbul
}

Specifying the type explicitly with as helps both the compiler and the reader.

Practice Print the name from JSON

Decode the string s with jsonDecode and print the value at the 'ad' key with print.

Starter code

main.dart
import 'dart:convert';

void main() {
  const s = '{"ad": "Deniz"}';
  // JSON dizesini çöz ve 'ad' değerini yazdır
}

Sample solution

main.dart
import 'dart:convert';

void main() {
  const s = '{"ad": "Deniz"}';
  final m = jsonDecode(s);
  print(m['ad']);
}

Expected output

Deniz

Questions and answers

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

1 What does the call jsonDecode('{"ad":"Ayşe"}') return?

  • A Future
  • A Widget
  • An object of type Map<String, dynamic> Correct answer
  • Always a String

Explanation: jsonDecode converts a JSON object to a Map and a JSON array to a List. Since the input is an object, the returned type is Map<String, dynamic>.

2 Decode the JSON string

Question
import 'dart:convert';

void main() {
  const s = '{"ad": "Ece"}';
  final m = ____(s);
  print(m['ad']);
}
Answer
import 'dart:convert';

void main() {
  const s = '{"ad": "Ece"}';
  final m = jsonDecode(s);
  print(m['ad']);
}

Explanation: jsonDecode is the JSON decoding function in dart:convert; it turns the string into a Map.

3 dart:convert parts

Term Meaning
jsonDecode Converts a JSON string to an object
dart:convert The library to import
Map<String, dynamic> Dart equivalent of a JSON object
m['ad'] Access to the 'ad' value in the Map

All lessons in Intermediate