1. What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight format used to store and exchange data between applications.
Example:
JSON is language-independent. You can use it with Rust, PHP, JavaScript, Python, Java, and many other programming languages.
JSON Data Types
JSON Type | Example |
|---|---|
String |
|
Number |
|
Boolean |
|
Array |
|
Object |
|
Null |
|
Note: JSON does not support comments or a separate date data type. Dates are usually stored as strings.
2. What is Serialization?
Serialization means converting a Rust data structure into a format that can be stored or transmitted, such as JSON.
For example:
Rust structure:
JSON output:
3. What is Deserialization?
Deserialization is the opposite process. It converts JSON data into a Rust data structure.
JSON:
Rust structure:
Difference
Serialization | Deserialization |
|---|---|
Rust to JSON | JSON to Rust |
Converts data into JSON | Converts JSON into Rust data |
Used for saving or sending data | Used for reading or receiving data |
4. Install Serde and serde_json
Rust does not include built-in JSON serialization in its standard library.
We use two popular libraries:
- Serde: A framework for serializing and deserializing data.
- serde_json: A library that provides JSON support through Serde.
Open your project terminal and run:
These commands add the dependencies to your Cargo.toml file.
5. Create a Rust Structure for JSON
We can use the Serialize and Deserialize traits with a Rust struct.
Explanation
Serializeallows Rust data to be converted into JSON.Deserializeallows JSON data to be converted into Rust data.Debugallows us to print the structure using{:?}.
6. Convert Rust Data into JSON
We can use serde_json::to_string() to convert a Rust structure into a JSON string.
Output
Pretty JSON Formatting
If you want readable, properly formatted JSON, use to_string_pretty().
Output:
7. Convert JSON into Rust Data
We can use serde_json::from_str() to convert JSON into a Rust structure.
Output
What is r#?
The r# syntax creates a raw string literal in Rust.
It allows us to write quotation marks and multiple lines without escaping every quotation mark.
8. Working with Dynamic JSON Using Value
Sometimes you do not know the exact JSON structure in advance.
In that situation, you can use serde_json::Value.
Output
You can also use .get() to safely access a property:
Value is useful when working with flexible JSON responses from APIs.
9. Create JSON Using the json! Macro
The json! macro lets you create JSON values directly.
You can also access its values:
10. Working with JSON Arrays
JSON arrays can be represented using Rust's Vec<T>.
Output
11. Rename JSON Fields
Sometimes the JSON property name is different from the Rust field name.
We can use #[serde(rename = "...")].
The JSON property is student_name, but the Rust field is name.
12. Handle Optional JSON Fields
Sometimes a JSON object may not contain every property.
You can use Option<T> for fields that may be missing or null.
Output
If the JSON contains an email address, the value will be Some("...").
13. Read and Write JSON Files
JSON is commonly used for storing application data.
Let's create a file named student.json.
Write JSON to a File
This creates a JSON file in your project's working directory.
Read JSON from a File
This reads the JSON file and converts its contents into a Rust structure.
14. Error Handling with Result
Avoid using unwrap() in production applications because it can cause the program to panic when an error occurs.
A better approach is to use Result and the ? operator.
Here:
Resultrepresents success or failure.?returns an error from the current function.Ok(())indicates successful completion.
15. Mini Project: Student Database Using JSON
Let's create a small student database that stores multiple student records in a JSON file.
Project Features
- Store student ID.
- Store student name.
- Store course name.
- Save multiple students.
- Read all students from the JSON file.
Complete Code
Expected Output
Important: This example adds two records every time you run it. For a real application, you should check whether a student already exists before adding a duplicate.
16. Important Rust JSON Functions
Function | Purpose |
|---|---|
| Convert Rust data into JSON |
| Convert Rust data into formatted JSON |
| Convert JSON string into Rust data |
| Convert JSON bytes into Rust data |
| Create JSON values |
| Work with dynamic JSON data |
17. Common Mistakes
- Forgetting to add the
serdeandserde_jsondependencies. - Forgetting
#[derive(Serialize, Deserialize)]. - Using the wrong Rust data type for a JSON field.
- Forgetting that JSON strings require double quotation marks.
- Using
unwrap()without considering possible errors. - Trying to deserialize a JSON property that does not match the Rust field name.
- Appending raw JSON objects to a file instead of updating the complete JSON array.
18. Practice Exercises
Try these exercises yourself:
- Create a
Productstruct withid,name, andprice. - Convert a product into JSON.
- Convert JSON into a
Productstructure. - Create a JSON array containing five products.
- Save product records in
products.json. - Read the product records from the file.
- Add an optional
descriptionfield usingOption<String>. - Rename the Rust field
product_nameto JSON fieldname.