serde_json Crate - Working with JSON in Rust

Learn what the serde_json crate is, how to add it to a Rust project, and how to convert between Rust structs and JSON data using practical examples for beginners.

The serde_json crate is the standard Rust library for working with JSON (JavaScript Object Notation) data. It builds on top of the serde crate, which provides the core traits for serialization and deserialization. If serde is the engine that knows how to move data in and out of Rust types, serde_json is the specific adapter that speaks the JSON format. You'll use it whenever you need to read JSON that someone sends to your server, or produce JSON to send back to a browser, mobile app, or another service.

JSON is a text format used everywhere on the web. It represents structured data with objects (key-value pairs) and arrays. For example, a JSON object describing a user might look like this:

{
  "id": 7,
  "name": "Alice",
  "active": true
}

In Rust, you'd likely represent that same user with a struct. The serde_json crate exists to bridge those two worlds: converting a Rust struct into a JSON string (serialization) and converting a JSON string into a Rust struct (deserialization). This page focuses on that crate alone. Everything here works anywhere in a Rust program, including inside an Axum handler.

Adding serde_json to Your Project

Before you can use serde_json, you must add it to your project's Cargo.toml file. The crate is published on crates.io, so you can add it with cargo add from the command line inside your project directory:

cargo add serde_json

Alternatively, you can edit Cargo.toml directly. Open the file and add the line under [dependencies]:

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

If you have been following along, you already have serde with the derive feature. That's important because serde_json needs the Serialize and Deserialize trait implementations that the derive macros generate. The serde_json crate itself does not provide those derives; it only knows how to use them once they exist.

Don't Skip the serde Dependency:

The serde_json crate depends on serde internally, but it does not automatically turn on the derive feature. If your struct uses #[derive(Serialize, Deserialize)], you must include serde with the derive feature in your own Cargo.toml. Otherwise, the compiler will not find the derive macros and you'll get errors like cannot find derive macro Serialize in this scope.

After adding the dependency, run cargo build to download and compile the crate. The next time you compile your project, serde_json will be available.

A First Serialization Example

Let's start with the simplest possible thing: taking a Rust struct and turning it into a JSON string. Create a new file or replace src/main.rs in your project with the following code. This assumes you have a project set up; if not, just create a new binary crate with cargo new json-demo.

src/main.rs
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u64,
    name: String,
    active: bool,
}
fn main() {
    let user = User {
        id: 7,
        name: String::from("Alice"),
        active: true,
    };
    let json_string = serde_json::to_string(&user).unwrap();
    println!("{}", json_string);
}

When you run this with cargo run, the output will be:

{"id":7,"name":"Alice","active":true}

This is JSON. It is compact, with no extra spaces or newlines. The serde_json::to_string function takes a reference to any value that implements the Serialize trait and returns a Result<String, serde_json::Error>. We call .unwrap() here for brevity; in a real application you would handle the error properly.

The order of fields in the JSON matches the order in your struct definition. JSON objects are unordered by specification, but the serialized output follows the struct's field order, which is useful for predictable output.

Deserialization: Turning JSON Back into a Struct

Now let's go the other direction. Suppose you receive a JSON string from a network request or read it from a file. You want to turn that string into a Rust struct so you can work with the data using typed fields.

src/main.rs
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u64,
    name: String,
    active: bool,
}
fn main() {
    let json_data = r#"
        {
            "id": 7,
            "name": "Alice",
            "active": true
        }
    "#;
    let user: User = serde_json::from_str(json_data).unwrap();
    println!("{:?}", user);
}

Running this prints:

User { id: 7, name: "Alice", active: true }

The serde_json::from_str function takes a string slice (&str) and a target type, and it returns a Result<T, serde_json::Error> where T is the type you specify. You must tell Rust what type you expect, either through a type annotation as shown (let user: User = ...) or through type inference from later usage.

The r#"..."# syntax in Rust is a raw string literal. It lets you write multi-line strings without escaping every quote. This is handy for embedding JSON examples in code.

The Many Ways to Serialize and Deserialize

serde_json provides several functions for different input and output formats. Which one you choose depends on where your data comes from and where it needs to go.

Each snippet below is a fragment from inside a function that returns a Result, which is why the ? operator works - the full programs earlier on this page show the complete shape, including the struct definition and the use lines.

Serializing to a String

You've already seen to_string, which produces a String. This is the most common case when you need to send JSON as a response body or log it for debugging.

let json_string = serde_json::to_string(&user)?;

Serializing to a Byte Vector

Sometimes you need the JSON as bytes instead of a UTF-8 string. For example, when writing to a network socket or a file, you often work with &[u8] (byte slices) or Vec<u8> (owned byte vectors). to_vec does this conversion:

let json_bytes: Vec<u8> = serde_json::to_vec(&user)?;

The resulting json_bytes is the same JSON text but stored as raw bytes. In memory, a Rust String is guaranteed to be valid UTF-8, which JSON always is, so the difference is mostly about what API you're using downstream.

Writing Directly to a Writer

If you're streaming data to a file, a network connection, or any type that implements the std::io::Write trait, you can avoid building the entire string in memory. Instead, use to_writer:

use std::fs::File;
let mut file = File::create("user.json")?;
serde_json::to_writer(&mut file, &user)?;

This writes the JSON directly into the file handle. It's more efficient for large data because it doesn't allocate a huge String first.

Deserializing from a String

from_str takes a &str and parses it. Use this when you have a complete string in memory.

let user: User = serde_json::from_str(json_string)?;

Deserializing from a Byte Slice

If your JSON arrives as a byte slice (for example, from a Vec<u8> received over the network), use from_slice:

let user: User = serde_json::from_slice(&json_bytes)?;

This avoids converting the bytes to a String first, which can save a little time when performance matters.

Deserializing from a Reader

For reading JSON from a file or another stream without first loading the whole input into a String, use from_reader with any type that implements std::io::Read:

use std::fs::File;
let file = File::open("user.json")?;
let user: User = serde_json::from_reader(file)?;

Under the hood, from_reader reads and parses the input incrementally instead of requiring the whole document as one string first. The parsed value itself still lives in memory, so this saves input buffering, not result storage.

Working with Dynamic JSON Using the json! Macro and Value

So far, you've seen conversion between strongly typed Rust structs and JSON. But sometimes you don't have a fixed struct in mind. Maybe you're building a JSON response on the fly, or you're parsing a JSON document where the shape can vary. For these cases, serde_json provides the Value enum and the json! macro.

The Value Enum

serde_json::Value is a recursive enum that can represent any valid JSON value. Its variants are:

  • Value::Null
  • Value::Bool(bool)
  • Value::Number(Number)
  • Value::String(String)
  • Value::Array(Vec<Value>)
  • Value::Object(Map<String, Value>)

This means you can hold JSON data without knowing its structure at compile time. You can inspect it, modify it, and then convert it back to a string.

use serde_json::Value;
let data = r#"
    {
        "name": "Alice",
        "age": 30,
        "hobbies": ["reading", "hiking"]
    }
"#;
let mut value: Value = serde_json::from_str(data).unwrap();
// Access a field
if let Some(name) = value.get("name") {
    println!("Name: {}", name);
}
// Add a new field
value["country"] = Value::String("Canada".to_string());
// Modify an existing field
value["age"] = Value::Number(31.into());
// Print the modified JSON
println!("{}", serde_json::to_string_pretty(&value).unwrap());

This prints:

{
  "age": 31,
  "country": "Canada",
  "hobbies": [
    "reading",
    "hiking"
  ],
  "name": "Alice"
}

Notice the key order: the keys come out alphabetically (age, country, hobbies, name), not in the order they were written or inserted.

Why the keys come out sorted:

By default, serde_json stores object keys in a BTreeMap, which keeps them sorted. If you need insertion order preserved, enable the preserve_order feature of serde_json (it uses an IndexMap instead). Struct serialization is not affected - fields come out in the order they are declared in the struct.

Notice the to_string_pretty function. It produces human-readable JSON with indentation and newlines, which is great for debugging or for saving to files that humans will read. The regular to_string produces compact JSON, which is better for network transmission.

The json! Macro

Writing out Value::Object, Value::Array, etc., can be verbose. The json! macro provides a much more concise syntax for creating Values directly from JSON-like literals.

use serde_json::json;
let user = json!({
    "id": 7,
    "name": "Alice",
    "active": true,
    "tags": ["admin", "editor"]
});
println!("{}", user);

The macro accepts JSON syntax and creates a Value. You can also use it to build JSON incrementally:

let mut response = json!({
    "status": "ok",
    "data": []
});
if let Some(arr) = response["data"].as_array_mut() {
    arr.push(json!({"id": 1, "title": "Hello"}));
    arr.push(json!({"id": 2, "title": "World"}));
}
println!("{}", serde_json::to_string_pretty(&response).unwrap());

The json! macro is often used in tests and small scripts where you want to quickly produce a JSON payload without defining a struct. In production code, you'll usually prefer typed structs because they give you compile-time checks and better performance, but Value and json! are invaluable for prototyping and for situations where the schema is truly dynamic.

Customizing Field Names and Handling Missing Data

JSON data often uses naming conventions that differ from Rust's. For example, a JSON API might use user_id (snake_case) while your Rust struct might name the field user_id too, but sometimes external APIs use camelCase like userId. The serde crate provides attributes that let you control how fields are mapped. Since serde_json relies on these attributes, it's worth showing a few common ones here.

Renaming Fields with rename

use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct ApiResponse {
    #[serde(rename = "userId")]
    user_id: u64,
    #[serde(rename = "fullName")]
    full_name: String,
}
fn main() {
    let response = ApiResponse {
        user_id: 1,
        full_name: "Alice Smith".into(),
    };
    let json = serde_json::to_string(&response).unwrap();
    println!("{}", json);
    // Output: {"userId":1,"fullName":"Alice Smith"}
}

When deserializing, the rename works in reverse: JSON with "userId" will be stored in user_id.

Handling Optional Fields

If a JSON object might or might not contain a certain key, use Option<T> in your struct. When deserializing, a missing key becomes None, and a present key becomes Some(value). When serializing, None becomes a field with value null unless you also use skip_serializing_if.

use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct UserProfile {
    username: String,
    bio: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    website: Option<String>,
}
fn main() {
    let profile = UserProfile {
        username: "alice".into(),
        bio: None,
        website: None,
    };
    let json = serde_json::to_string(&profile).unwrap();
    println!("{}", json);
    // Output: {"username":"alice","bio":null}
    // Notice website is skipped because it is None and skip_serializing_if is set.
}

Without skip_serializing_if, website would appear as "website":null. With it, the field is omitted entirely when the value is None. This is often what you want when talking to APIs that treat a missing field differently from a null field.

Providing Defaults for Missing Fields

If your Rust struct has a field that is not Option but the JSON might omit it, you can use #[serde(default)] to fill it with the type's default value (for example, 0 for integers, "" for strings, false for booleans). You can also provide a custom default function.

use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Settings {
    theme: String,
    #[serde(default)]
    notifications_enabled: bool,
    #[serde(default = "default_retries")]
    max_retries: u32,
}
fn default_retries() -> u32 {
    3
}
fn main() {
    let json_data = r#"{"theme":"dark"}"#;
    let settings: Settings = serde_json::from_str(json_data).unwrap();
    println!("{:?}", settings);
    // Output: Settings { theme: "dark", notifications_enabled: false, max_retries: 3 }
}

Without default, deserialization would fail because the JSON is missing the field and there is no Option to absorb the absence. These attributes give you control over how strict or lenient your parsing should be.

Common Errors and How to Handle Them

When parsing or serializing goes wrong, serde_json returns a serde_json::Error. This error type implements Display and often includes a helpful message with line and column information about where the JSON was malformed.

Error Example: Invalid JSON

fn main() {
    let bad_json = "{ not valid json }";
    let result: Result<serde_json::Value, _> = serde_json::from_str(bad_json);
    match result {
        Ok(v) => println!("Parsed: {}", v),
        Err(e) => println!("Failed to parse: {}", e),
    }
}

The output will include something like key must be a string at line 1 column 3. The serde_json::Error also has methods to inspect the line and column:

let bad_json = "{ not valid json }";
if let Err(e) = serde_json::from_str::<serde_json::Value>(bad_json) {
    println!("Error at line {} column {}", e.line(), e.column());
    println!("Full error: {}", e);
}

Error Example: Type Mismatch

If the JSON is valid but doesn't match the expected Rust type, you'll get an error too.

use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Person {
    age: u32,
}
fn main() {
    let json_data = r#"{"age": "not a number"}"#;
    let result: Result<Person, _> = serde_json::from_str(json_data);
    match result {
        Ok(p) => println!("{:?}", p),
        Err(e) => println!("Type error: {}", e),
    }
}

The exact error is invalid type: string "not a number", expected u32 at line 1 column 22. It names the type it found, the type it wanted, and the exact position. These errors are extremely useful during development.

Unwrap Is Only for Examples:

In all the examples above, we used .unwrap() for simplicity. In a real application, especially in a server that must stay running, you should handle these Results gracefully. A failed deserialization should become an error response to the client - a 400 Bad Request for malformed JSON, a 422 Unprocessable Entity when the JSON is valid but does not match your struct - not a panic that crashes your server. For now, remember that unwrap is a shortcut that stops execution if something goes wrong.

When You See JSON Output, It Worked:

A sure sign that your serialization worked is seeing a JSON string that exactly matches the field names and types from your struct. If you see {"id":7,"name":"Alice","active":true} and that's what you expected, the crate is doing its job correctly.

A Complete Practical Example: Reading, Modifying, and Writing JSON

Let's combine everything into one realistic scenario. Imagine you are building a small command-line tool that reads a JSON configuration file, updates a value, and writes the result back to disk. This exercises reading a file into a string, Value manipulation, and writing pretty JSON back to disk.

src/main.rs
use serde_json::{json, Value};
use std::fs::File;
use std::io::{Read, Write};
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Read the file into a string
    let mut file = File::open("config.json")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    // 2. Parse the string into a Value
    let mut config: Value = serde_json::from_str(&contents)?;
    // 3. Modify the config
    config["server"]["port"] = json!(8080);
    config["debug"] = Value::Bool(true);
    // 4. Serialize back to a pretty string
    let pretty_json = serde_json::to_string_pretty(&config)?;
    // 5. Write to a new file
    let mut output = File::create("config_updated.json")?;
    output.write_all(pretty_json.as_bytes())?;
    println!("Updated config written to config_updated.json");
    Ok(())
}

Create a config.json file in the same directory with this content:

config.json
{
  "server": {
    "host": "127.0.0.1",
    "port": 3000
  },
  "debug": false
}

Run the program. It will create config_updated.json with:

config_updated.json
{
  "debug": true,
  "server": {
    "host": "127.0.0.1",
    "port": 8080
  }
}

The keys are alphabetically sorted (debug before server) because Value objects are stored in a sorted map by default - see the note above about preserve_order.

This example demonstrates the complete round-trip: reading JSON from disk, parsing it into a flexible Value, changing values, and writing it back out in a human-readable format. Even though you don't have a fixed struct for the entire config, serde_json still gives you safe access through the Value type and the json! macro.

If you wanted to work with a typed struct instead, you would define a struct that matches the shape of the JSON and derive Serialize and Deserialize. That approach is preferred when you know the schema in advance because it catches mistakes at compile time. The Value approach is for when the schema is unknown or varies.

Summary

The serde_json crate is the bridge between Rust's type system and the JSON data format. It provides functions to serialize Rust values into JSON strings, byte vectors, or writers, and to deserialize JSON from strings, byte slices, or readers. Its Value enum and json! macro give you a dynamic way to work with JSON when you don't have a fixed schema.

This crate works closely with serde's derive macros, so any struct with #[derive(Serialize, Deserialize)] can be converted automatically. You've seen how to handle field naming differences, optional fields, and defaults. You've also learned that errors are an important part of the API, and real programs should handle them properly instead of panicking.

Now that you understand serde_json itself, you can use it anywhere in your Rust program. When you later build Axum handlers that accept JSON request bodies or return JSON responses, the same concepts apply - Axum's Json extractor and response type simply wrap serde_json under the hood, so the knowledge from this page transfers directly. The decision is simple: if the shape of the JSON is fixed, define a struct and derive the traits; if the shape varies or is unknown, reach for Value and json!.