Working with JSON in Rust
In this lesson, you will learn how to read, write, serialize, and deserialize JSON data in Rust. JSON is one of the most common formats used for data exchange in APIs, configuration files, and web applications.
Rust handles JSON safely and efficiently using the popular serde ecosystem.
What Is JSON?
JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read and machines to parse.
It represents data using:
- Objects (key–value pairs)
- Arrays
- Strings, numbers, booleans, and null
Why Use JSON in Rust?
JSON is widely used for:
- REST APIs
- Configuration files
- Data exchange between services
- Web and backend applications
Rust’s strong typing combined with JSON serialization ensures data safety.
Required Crates
To work with JSON in Rust, you need two crates:
serde– serialization frameworkserde_json– JSON support
Add the following to your Cargo.toml file:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Creating a Struct for JSON Data
Rust maps JSON objects to structs using the Serialize and Deserialize traits.
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u32,
active: bool,
}
Serializing Rust Data to JSON
Serialization converts a Rust struct into JSON.
use serde_json;
fn main() {
let user = User {
name: String::from("Alice"),
age: 30,
active: true,
};
let json = serde_json::to_string(&user).unwrap();
println!("{}", json);
}
This converts the struct into a JSON string.
Pretty Printing JSON
For better readability, use pretty formatting.
let pretty = serde_json::to_string_pretty(&user).unwrap();
println!("{}", pretty);
Deserializing JSON into Rust Structs
Deserialization converts JSON back into Rust types.
let data = r#"
{
"name": "Bob",
"age": 25,
"active": false
}
"#;
let user: User = serde_json::from_str(data).unwrap();
println!("{}", user.name);
Reading JSON from a File
You can read JSON directly from a file.
use std::fs;
let content = fs::read_to_string("user.json").unwrap();
let user: User = serde_json::from_str(&content).unwrap();
Writing JSON to a File
To store JSON data, write it to a file.
use std::fs;
let json = serde_json::to_string_pretty(&user).unwrap();
fs::write("output.json", json).unwrap();
Using Dynamic JSON Values
Sometimes you don’t know the structure in advance.
Use serde_json::Value for dynamic JSON.
use serde_json::Value;
let raw = r#"{ "language": "Rust", "year": 2015 }"#;
let v: Value = serde_json::from_str(raw).unwrap();
println!("{}", v["language"]);
Error Handling with JSON
Use Result to safely handle JSON errors.
fn main() -> Result<(), Box> {
let text = std::fs::read_to_string("data.json")?;
let user: User = serde_json::from_str(&text)?;
println!("{}", user.name);
Ok(())
}
Why Serde Is Powerful
Serde provides:
- Fast serialization
- Strong type safety
- Customizable mappings
- Industry-wide adoption
📝 Practice Exercises
Exercise 1
Create a struct and convert it to JSON.
Exercise 2
Read JSON data from a string and deserialize it.
Exercise 3
Write a JSON object to a file.
Exercise 4
Access a field using serde_json::Value.
✅ Practice Answers
Answer 1
let json = serde_json::to_string(&user).unwrap();
Answer 2
let obj: User = serde_json::from_str(json_data).unwrap();
Answer 3
std::fs::write("data.json", json).unwrap();
Answer 4
println!("{}", value["key"]);
What’s Next?
In the next lesson, you will learn about Testing in Rust, including unit tests, integration tests, and best practices.