Rust
December 2, 2026 8 min read

JSON and Serialization in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format used to store and exchange data between applications.

Example:

{
"id": 101,
"name": "Rahul",
"course": "Rust Programming",
"fees": 5000
}

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

"Rahul"

Number

100 or 25.5

Boolean

true or false

Array

[10, 20, 30]

Object

{"name": "Rahul"}

Null

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:

struct Student {
id: u32,
name: String,
}

JSON output:

{
"id": 101,
"name": "Rahul"
}

3. What is Deserialization?

Deserialization is the opposite process. It converts JSON data into a Rust data structure.

JSON:

{
"id": 101,
"name": "Rahul"
}

Rust structure:

Student {
id: 101,
name: String::from("Rahul"),
}

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:

  1. Serde: A framework for serializing and deserializing data.
  2. serde_json: A library that provides JSON support through Serde.

Open your project terminal and run:

cargo add serde --features derive
cargo add serde_json

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.

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
struct Student {
id: u32,
name: String,
course: String,
fees: f64,
}

fn main() {
let student = Student {
id: 101,
name: String::from("Rahul"),
course: String::from("Rust"),
fees: 5000.0,
};

println!("{:?}", student);
}

Explanation

  1. Serialize allows Rust data to be converted into JSON.
  2. Deserialize allows JSON data to be converted into Rust data.
  3. Debug allows 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.

use serde::Serialize;

#[derive(Serialize)]
struct Student {
id: u32,
name: String,
course: String,
}

fn main() {
let student = Student {
id: 101,
name: String::from("Rahul"),
course: String::from("Rust"),
};

let json = serde_json::to_string(&student).unwrap();

println!("{}", json);
}

Output

{"id":101,"name":"Rahul","course":"Rust"}

Pretty JSON Formatting

If you want readable, properly formatted JSON, use to_string_pretty().

let json = serde_json::to_string_pretty(&student).unwrap();

println!("{}", json);

Output:

{
"id": 101,
"name": "Rahul",
"course": "Rust"
}

7. Convert JSON into Rust Data

We can use serde_json::from_str() to convert JSON into a Rust structure.

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Student {
id: u32,
name: String,
course: String,
}

fn main() {
let json = r#"
{
"id": 101,
"name": "Rahul",
"course": "Rust"
}
"#;

let student: Student = serde_json::from_str(json).unwrap();

println!("{:?}", student);
println!("Student Name: {}", student.name);
}

Output

Student { id: 101, name: "Rahul", course: "Rust" }
Student Name: Rahul

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.

use serde_json::Value;

fn main() {
let json = r#"
{
"name": "Rahul",
"age": 25,
"active": true
}
"#;

let data: Value = serde_json::from_str(json).unwrap();

println!("{}", data["name"]);
println!("{}", data["age"]);
println!("{}", data["active"]);
}

Output

"Rahul"
25
true

You can also use .get() to safely access a property:

if let Some(name) = data.get("name") {
println!("{}", name);
}

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.

use serde_json::json;

fn main() {
let student = json!({
"id": 101,
"name": "Rahul",
"course": "Rust",
"active": true
});

println!("{}", student);
}

You can also access its values:

println!("{}", student["name"]);

10. Working with JSON Arrays

JSON arrays can be represented using Rust's Vec<T>.

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
struct Student {
id: u32,
name: String,
}

fn main() {
let students = vec![
Student {
id: 1,
name: String::from("Rahul"),
},
Student {
id: 2,
name: String::from("Amit"),
},
Student {
id: 3,
name: String::from("Priya"),
},
];

let json = serde_json::to_string_pretty(&students).unwrap();

println!("{}", json);
}

Output

[
{
"id": 1,
"name": "Rahul"
},
{
"id": 2,
"name": "Amit"
},
{
"id": 3,
"name": "Priya"
}
]

11. Rename JSON Fields

Sometimes the JSON property name is different from the Rust field name.

We can use #[serde(rename = "...")].

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Student {
#[serde(rename = "student_name")]
name: String,
}

fn main() {
let json = r#"
{
"student_name": "Rahul"
}
"#;

let student: Student = serde_json::from_str(json).unwrap();

println!("{}", student.name);
}

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.

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Student {
name: String,
email: Option<String>,
}

fn main() {
let json = r#"
{
"name": "Rahul"
}
"#;

let student: Student = serde_json::from_str(json).unwrap();

println!("Name: {}", student.name);
println!("Email: {:?}", student.email);
}

Output

Name: Rahul
Email: None

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

use serde::Serialize;
use std::fs;

#[derive(Serialize)]
struct Student {
id: u32,
name: String,
course: String,
}

fn main() {
let student = Student {
id: 101,
name: String::from("Rahul"),
course: String::from("Rust"),
};

let json = serde_json::to_string_pretty(&student).unwrap();

fs::write("student.json", json).unwrap();

println!("Student data saved!");
}

This creates a JSON file in your project's working directory.

Read JSON from a File

use serde::Deserialize;
use std::fs;

#[derive(Debug, Deserialize)]
struct Student {
id: u32,
name: String,
course: String,
}

fn main() {
let json = fs::read_to_string("student.json").unwrap();

let student: Student = serde_json::from_str(&json).unwrap();

println!("{:?}", student);
}

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.

use serde::{Serialize, Deserialize};
use std::fs;

#[derive(Debug, Serialize, Deserialize)]
struct Student {
id: u32,
name: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
let student = Student {
id: 101,
name: String::from("Rahul"),
};

let json = serde_json::to_string_pretty(&student)?;

fs::write("student.json", json)?;

println!("JSON saved successfully!");

Ok(())
}

Here:

  1. Result represents success or failure.
  2. ? returns an error from the current function.
  3. 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

  1. Store student ID.
  2. Store student name.
  3. Store course name.
  4. Save multiple students.
  5. Read all students from the JSON file.

Complete Code

use serde::{Serialize, Deserialize};
use std::fs;

#[derive(Debug, Serialize, Deserialize)]
struct Student {
id: u32,
name: String,
course: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {

let mut students: Vec<Student> = match fs::read_to_string("students.json") {
Ok(content) => serde_json::from_str(&content)?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
Vec::new()
}
Err(error) => return Err(error.into()),
};

// Add a new student
students.push(Student {
id: 1,
name: String::from("Rahul"),
course: String::from("Rust"),
});

students.push(Student {
id: 2,
name: String::from("Amit"),
course: String::from("Python"),
});

// Convert students into JSON
let json = serde_json::to_string_pretty(&students)?;

// Save JSON to file
fs::write("students.json", json)?;

println!("Student records saved!");

// Read and display records
let content = fs::read_to_string("students.json")?;

let records: Vec<Student> = serde_json::from_str(&content)?;

println!("\nStudent Records:");

for student in records {
println!(
"ID: {}, Name: {}, Course: {}",
student.id,
student.name,
student.course
);
}

Ok(())
}

Expected Output

Student records saved!

Student Records:
ID: 1, Name: Rahul, Course: Rust
ID: 2, Name: Amit, Course: Python

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

to_string()

Convert Rust data into JSON

to_string_pretty()

Convert Rust data into formatted JSON

from_str()

Convert JSON string into Rust data

from_slice()

Convert JSON bytes into Rust data

json!()

Create JSON values

Value

Work with dynamic JSON data

17. Common Mistakes

  1. Forgetting to add the serde and serde_json dependencies.
  2. Forgetting #[derive(Serialize, Deserialize)].
  3. Using the wrong Rust data type for a JSON field.
  4. Forgetting that JSON strings require double quotation marks.
  5. Using unwrap() without considering possible errors.
  6. Trying to deserialize a JSON property that does not match the Rust field name.
  7. Appending raw JSON objects to a file instead of updating the complete JSON array.

18. Practice Exercises

Try these exercises yourself:

  1. Create a Product struct with id, name, and price.
  2. Convert a product into JSON.
  3. Convert JSON into a Product structure.
  4. Create a JSON array containing five products.
  5. Save product records in products.json.
  6. Read the product records from the file.
  7. Add an optional description field using Option<String>.
  8. Rename the Rust field product_name to JSON field name.