Dart JSON
Dart JSON
JSON (JavaScript Object Notation) is a text format for storing and sending data.
Apps and websites use JSON to send data to each other, for example when an app gets the weather from a server.
This is what JSON looks like:
{"name": "Anna", "age": 31, "languages": ["Dart", "Python"]}
JSON looks a lot like a Dart map and list, but it is only text, a String.
The dart:convert library has two functions to go between Dart objects and JSON:
jsonEncode()turns a Dart object into a JSON string.jsonDecode()turns a JSON string into a Dart object.
Map to JSON
To turn a map into JSON, use jsonEncode().
The result is a normal string, so you can save it in a file or send it over the internet:
Example
import 'dart:convert';
void main() {
Map<String, dynamic> person = {
'name': 'Anna',
'age': 31,
'student': false,
'languages': ['Dart', 'Python'],
};
String json = jsonEncode(person);
print(json);
print(json.runtimeType);
}
Try it Yourself »
Result:
{"name":"Anna","age":31,"student":false,"languages":["Dart","Python"]}
String
Notice that JSON always uses double quotes around strings.
You can encode strings, numbers, booleans, null, lists and maps with string keys.
To make the JSON easier to read, use a JsonEncoder with an indent:
Example
import 'dart:convert';
void main() {
Map<String, dynamic> car = {'brand': 'Volvo', 'year': 2024, 'electric': true};
JsonEncoder encoder = JsonEncoder.withIndent(' ');
print(encoder.convert(car));
}
Try it Yourself »
Result:
{
"brand": "Volvo",
"year": 2024,
"electric": true
}
JSON to Map
To read JSON, use jsonDecode().
A JSON object becomes a Map<String, dynamic>, and you can read the values with their keys:
Example
import 'dart:convert';
void main() {
String json = '{"name": "Liam", "age": 25, "city": "Oslo"}';
Map<String, dynamic> user = jsonDecode(json);
print(user['name']);
print(user['age'] + 1);
print(user['city']);
}
Try it Yourself »
Result:
Liam
26
Oslo
The type dynamic means that the value can be of any type, because Dart cannot know the types in a JSON string before it reads it.
A JSON array becomes a Dart List:
Example
import 'dart:convert';
void main() {
String json = '[{"fruit": "Apple", "price": 3}, {"fruit": "Banana", "price": 2}]';
List<dynamic> items = jsonDecode(json);
for (var item in items) {
print('${item['fruit']} costs ${item['price']} dollars');
}
}
Try it Yourself »
Result:
Apple costs 3 dollars
Banana costs 2 dollars
Invalid JSON
If the string is not valid JSON, jsonDecode() throws a FormatException.
Use try and catch when the JSON comes from outside your program:
Example
import 'dart:convert';
void main() {
String json = "{'name': 'Liam'}";
try {
var data = jsonDecode(json);
print(data);
} on FormatException {
print('This is not valid JSON');
}
}
Try it Yourself »
Result:
This is not valid JSON
This JSON is not valid, because it uses single quotes.
Classes and JSON
In real programs, you often want to turn JSON into an object of your own class, and back again.
The common way to do this is to give the class two members:
- A
toJson()method that returns a map. - A factory constructor called
fromJson()that creates an object from a map.
Example
import 'dart:convert';
class Book {
final String title;
final int pages;
Book(this.title, this.pages);
factory Book.fromJson(Map<String, dynamic> json) {
return Book(json['title'] as String, json['pages'] as int);
}
Map<String, dynamic> toJson() {
return {'title': title, 'pages': pages};
}
}
void main() {
Book book = Book.fromJson(jsonDecode('{"title": "Dune", "pages": 412}'));
print('${book.title} has ${book.pages} pages');
Book newBook = Book('Emma', 474);
print(jsonEncode(newBook.toJson()));
}
Try it Yourself »
Result:
Dune has 412 pages
{"title":"Emma","pages":474}
The as String and as int parts tell Dart the type of each value, so the fields get the right type.
Tip: If an object has a toJson() method, jsonEncode() calls it for you.
So jsonEncode(newBook) gives the same result as jsonEncode(newBook.toJson()).