CodeBlanks Logo Icon CodeBlanks

jsonEncode

Serialize a Map to JSON string with jsonEncode.

Encode a Map to JSON with jsonEncode

To turn a Map back into a JSON string you use jsonEncode, also from dart:convert. It is handy when writing data to a file or sending it to a server.

import 'dart:convert';

final map = {'ad': 'Mert', 'yas': 30};
final s = jsonEncode(map);
print(s);  // {"ad":"Mert","yas":30}

The output is standard JSON with double quotes; the single quotes used in Dart become double quotes in JSON.

The type returned by jsonEncode

jsonEncode also turns numbers, strings, bools, and lists into JSON. The returned value is always a String in standard JSON format.

final s = jsonEncode([1, 2, 3]);
print(s);  // [1,2,3]
print(s.runtimeType);  // String

You can later turn this string back into an object with jsonDecode.

Practice Print the Map as JSON

Encode the map into a JSON string with jsonEncode and print it with print.

Starter code

main.dart
import 'dart:convert';

void main() {
  final map = {'ad': 'Selin', 'yas': 25};
  // map'i JSON dizesine çevir ve yazdır
}

Sample solution

main.dart
import 'dart:convert';

void main() {
  final map = {'ad': 'Selin', 'yas': 25};
  final s = jsonEncode(map);
  print(s);
}

Expected output

{"ad":"Selin","yas":25}

Questions and answers

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

1 What input does jsonEncode convert to a JSON string?

  • A Widget tree
  • A Future object
  • Only an int
  • A Map or List Correct answer

Explanation: jsonEncode converts a Map, List, number, string, or bool into a JSON string. The most common inputs are Map and List.

2 Encode the Map to JSON

Question
import 'dart:convert';

void main() {
  final map = {'sehir': 'İzmir'};
  final s = ____(map);
  print(s);
}
Answer
import 'dart:convert';

void main() {
  final map = {'sehir': 'İzmir'};
  final s = jsonEncode(map);
  print(s);
}

Explanation: jsonEncode turns a Map into a standard JSON string.

3 Encoding parts

Term Meaning
jsonEncode Converts an object to a JSON string
String The type returned by jsonEncode
{"ad":"Mert"} JSON output of the Map
dart:convert Library that contains jsonEncode

All lessons in Intermediate