Async and Practical
JSON Encode
Dart values to JSON text
jsonEncode from dart:convert walks a Dart Map/List/scalar and returns the equivalent JSON text. Maps preserve their insertion order and inner List values are encoded element by element.
Program
Play the program to build a small user map and encode it.
json_encode.dart
Replay: real traced execution (multi-file project)
import 'dart:convert';
void main() {
var user = {'name': 'Ada', 'scores': [9, 12, 6]};
var encoded = jsonEncode(user);
print('json = $encoded');
}
user ← {name: Ada, scores: [9, 12, 6]}
3void main() {4 var user = {'name': 'Ada', 'scores': [9, 12, 6]};5 var encoded = jsonEncode(user);values this step{name: Ada, scores: [9, 12, 6]}userencoded ← {"name":"Ada","scores":[9,12,6]}
4var user = {'name': 'Ada', 'scores': [9, 12, 6]};5var encoded = jsonEncode(user);6print('json = $encoded');values this step{"name":"Ada","scores":[9,12,6]}encodedprint('json = $encoded');
5 var encoded = jsonEncode(user);6 print('json = $encoded');7}outputjson = {"name":"Ada","scores":[9,12,6]}values this step{"name":"Ada","scores":[9,12,6]}encoded
dart:convert
`import 'dart:convert'` brings in `jsonEncode` and `jsonDecode`.
jsonEncode
`jsonEncode(value)` returns a JSON-text `String` representing the map, list, or scalar.
nested list
The `scores` list is encoded element by element inside the surrounding object.