JSON Parsing in Dart : A comprehensive guide
JSON parsing is a crucial skill for Dart developers, as JSON (JavaScript Object Notation) is a widely used data format for communication between web services and mobile apps.
Understanding how to parse JSON data in Dart is essential for working with APIs and handling server responses effectively.
In this tutorial, we will explore the world of JSON parsing in Dart and learn how to extract meaningful information from JSON strings.
What is JSON?
SON, short for JavaScript Object Notation, is a lightweight data interchange format. It is designed to be both human-readable and machine-readable.
JSON data is organized in key-value pairs and resembles JavaScript objects. It utilizes curly braces { } to encapsulate objects and square brackets [ ] for arrays.
This simplicity makes it easy for humans to read and write, while also being easily parsed and generated by machines.
To simplify JSON parsing in Dart, we will utilize the dart:convert library. This library provides a set of utilities for working with JSON data. To import the necessary packages, open your project’s pubspec.yaml file and add the following dependency:
dependencies:
dart:convert: ^2.0.0
Reading JSON Data from a File
To get started, let’s read JSON data from a file. Create a new file called person.json in your project’s directory [eg location : assets/json/person.json] and populate it with some sample JSON data.
person.json
{
"name": "Nikin",
"age" : 39,
"email": "nikin@example.com"
}
Now, let’s write the code to read the JSON data from the file
import 'dart:convert';
import 'dart:io';
void main()
{
final file = File('assets/json/person.json');
final jsonData = file.readAsStringSync();
final data = jsonDecode(jsonData);
print("Name :${data['name']}");
print("Email :${data['email']}");
print("Age: ${data['age']}");
}
Output
Name :Nikin
Email :nikin@example.com
Age: 39
Parsing JSON Data
With the JSON data stored in the jsonData variable, we can now parse it into Dart objects.
Dart provides a convenient method called jsonDecode() from the dart:convert library for parsing JSON strings.
Once the JSON data is parsed, we can access its values using the keys, similar to how we would interact with a regular Dart map.
This allows us to perform various operations such as printing values, manipulating the data, or displaying it in our app’s user interface.
Let’s convert the above code into an asynchronous program
To convert your code into an asynchronous program using async/await, you can make the main function asynchronous and utilize the File and jsonDecode methods in an asynchronous manner.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final file = File('assets/json/person.json');
final jsonData = await file.readAsString();
final data = jsonDecode(jsonData);
print("Name: ${data['name']}");
print("Email: ${data['email']}");
print("Age: ${data['age']}");
}
The main function is marked as asynchronous by adding the async keyword after Future<void>.
The readAsStringSync() method is replaced with await file.readAsString(). The readAsString() method returns a Future, so we use the await keyword to asynchronously wait for the file to be read and get the JSON data.
The jsonDecode method is still used as before to parse the JSON data into a Dart object.
Let’s consider the following JSON file called pdata.json
[
{
"full name": "Dianne Hayes",
"address": {
"street": "523 Bednar Knolls",
"city": "Tarrafal"
}
},
{
"full name": "Irma Kub",
"address": {
"street": "8225 Arden Cliff",
"city": "Parakai"
}
},
{
"full name": "Derek Schimmel",
"address": {
"street": "27589 Briana Summit",
"city": "Bruflat"
}
},
{
"full name": "Raymond Von",
"address": {
"street": "9371 Alice Forges",
"city": "Dangriga"
}
},
{
"full name": "Clay Bernhard",
"address": {
"street": "6345 Brigitte Locks",
"city": "Mizdah"
}
}
]
How to print the full names of all individuals whose names start with ‘D‘ from the given JSON data in Dart?
Solution (Code)
import 'dart:convert';
import 'dart:io';
void main()
{
final file = File('assets/json/pdata.json');
final jsonData = file.readAsStringSync();
final data = jsonDecode(jsonData);
final filteredNames = data.where((item) =>
(item['full name'] as String).startsWith('D'));
for(var item in filteredNames)
{
print(item['full name']);
}
}
Output
Dianne Hayes
Derek Schimmel
jsonDecode() to parse the jsonData string into a Dart object. The resulting object is stored in the variable data.
The where() method is called on the data object, which is assumed to be a list or iterable of elements.
Inside the where() method, a function is passed as an argument. This function takes each element item and checks if the value of item[‘full name’], after being explicitly cast to a string (item[‘full name’] as String), starts with the letter ‘D’. The result is a boolean value.
This for loop iterates over each element in filteredNames.Inside the loop, it retrieves the value associated with the key ‘full name’ from each item object and prints it using print().