Languages Knowledge Base

Working with JSON in Rust using serde_json

Complete Rust JSON guide: serde_json parsing with serde::Deserialize, serializing via Serialize derive macros, and dynamic serde_json::Value.

In Rust, use the serde_json crate. Derive #[derive(Serialize, Deserialize)] on your structs, then call serde_json::from_str(&text) to parse and serde_json::to_string_pretty(&obj) to produce formatted JSON.

JSON in Rust with serde_json

Rust uses the serde ecosystem for serialization. Add these to your Cargo.toml:

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Typed Deserialization

Derive #[derive(Deserialize)] on your struct, then call serde_json::from_str(&text)?.

Dynamic JSON with Value

Use serde_json::Value for parsing arbitrary/unknown JSON structures without defining a struct.

json
use serde::{Deserialize, Serialize};
use serde_json;

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

fn main() -> Result<(), serde_json::Error> {
    // Parse typed JSON
    let json = r#"{"id":1,"name":"Alice","is_active":true}"#;
    let user: User = serde_json::from_str(json)?;
    println!("{}", user.name); // Alice

    // Serialize to JSON string
    let serialized = serde_json::to_string(&user)?;

    // Pretty print
    let pretty = serde_json::to_string_pretty(&user)?;
    println!("{}", pretty);

    // Dynamic Value
    let value: serde_json::Value = serde_json::from_str(json)?;
    println!("{}", value["name"]); // "Alice"

    Ok(())
}

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I add serde_json to a Rust project?

Add serde = { version = "1", features = ["derive"] } and serde_json = "1" to your Cargo.toml dependencies.

How do I pretty print JSON in Rust?

Use serde_json::to_string_pretty(&obj).

What is serde_json::Value?

serde_json::Value is a Rust enum that can represent any valid JSON value without requiring a pre-defined struct.

Related JSON Topics & Reference Articles