Rust Playbook

Course › Week 3 · Iterators, real data, speed › Day 3 · lesson 17 of 42 · 20 min reading + 45–60 min practice

serde and JSON

Typed json_encode and json_decode with derive.

serdeserde_jsonSerializeDeserialize

On this page
  1. Setup
  2. 1. Struct to JSON
  3. 2. JSON to struct
  4. 3. When the JSON does not fit
  5. 4. Matching an API’s names
  6. 5. Optional fields and defaults
  7. 6. Enums as strings, and nested data
  8. 7. serde_json::Value: when the shape is not known
  9. Coming from PHP
  10. Practice
  11. Remember

Every tool from here on reads or writes JSON: csv2json writes it, the Laravel worker receives it, the axum service speaks it. In Rust that is serde (SERialize, DEserialize), plus serde_json for the JSON format itself. Almost every Rust project that touches data uses them.

The idea in one line: you describe the data as a struct, derive two traits, and serde writes the conversion code at compile time. json_decode gives you an untyped array; serde gives you your struct, or an error saying exactly what did not fit.

Setup

terminal
cargo add serde --features derive
cargo add serde_json

Every program below uses these two. serde is the framework; serde_json is one format for it. The same derives work with CSV tomorrow, without changing the struct.

1. Struct to JSON

#[derive(Serialize)] and the struct can be written as JSON. to_string gives compact JSON, to_string_pretty the readable kind. Both return a Result.

src/main.rs
use serde::Serialize;

#[derive(Serialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
    total_cents: u64,
}

fn main() -> Result<(), serde_json::Error> {
    let booking = Booking {
        id: 5521,
        guest: String::from("Lina"),
        nights: 3,
        total_cents: 45_030,
    };

    println!("{}", serde_json::to_string(&booking)?);
    println!("{}", serde_json::to_string_pretty(&booking)?);
    Ok(())
}
$ cargo run
{"id":5521,"guest":"Lina","nights":3,"total_cents":45030}
{
  "id": 5521,
  "guest": "Lina",
  "nights": 3,
  "total_cents": 45030
}

Field names become keys, as they are written. Serialising a plain struct like this cannot actually fail; the Result is there for cases that can, like a map whose keys cannot be written as JSON strings.

2. JSON to struct

#[derive(Deserialize)] and serde_json::from_str build the struct from text. The type of the variable tells it which struct to build, as with parse() and collect().

src/main.rs
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
}

fn main() -> Result<(), serde_json::Error> {
    let json = r#"{"id": 5521, "guest": "Lina", "nights": 3, "source": "airbnb"}"#;

    let booking: Booking = serde_json::from_str(json)?;
    println!("{booking:?}");
    println!(
        "#{}: {} stays {} nights",
        booking.id, booking.guest, booking.nights
    );
    Ok(())
}
$ cargo run
Booking { id: 5521, guest: "Lina", nights: 3 }
#5521: Lina stays 3 nights

r#"…"# is a raw string: quotes inside need no backslashes, which is what you want for JSON in code.

The "source" key is not in the struct, and it was ignored. That is serde’s default: take what you described, skip the rest. #[serde(deny_unknown_fields)] on the struct makes extra keys an error instead.

3. When the JSON does not fit

A missing field, or a value of the wrong type, is an Err, and its message says which field and where:

src/main.rs
use serde::Deserialize;

#[derive(Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
}

fn main() {
    let inputs = [
        r#"{"id": 5521, "guest": "Lina"}"#,
        r#"{"id": 5521, "guest": "Lina", "nights": "three"}"#,
        r#"{"id": 5521, "guest": "Lina", "nights": -1}"#,
        r#"{"id": 5521, "guest": "Lina", "nights": 3"#,
    ];
    for json in inputs {
        match serde_json::from_str::<Booking>(json) {
            Ok(b) => println!("ok: #{} {} for {} nights", b.id, b.guest, b.nights),
            Err(error) => println!("rejected: {error}"),
        }
    }
}
$ cargo run
rejected: missing field `nights` at line 1 column 29
rejected: invalid type: string "three", expected u32 at line 1 column 47
rejected: invalid value: integer `-1`, expected u32 at line 1 column 42
rejected: EOF while parsing an object at line 1 column 41

-1 is rejected because nights is a u32: the type is the validation. In PHP, json_decode would have given you -1, "three" and a missing key without complaint, and the bug would surface wherever the value was used.

from_str::<Booking> is the turbofish from yesterday: there is no variable to put the type on inside a match.

4. Matching an API’s names

Rust fields are snake_case; a JavaScript or Laravel API may send camelCase. #[serde(rename_all = "camelCase")] converts every field, both ways. #[serde(rename = "…")] renames one field, for example to a word Rust reserves, like type.

src/main.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Payout {
    booking_id: u64,
    total_cents: u64,
    #[serde(rename = "type")]
    kind: String,
}

fn main() -> Result<(), serde_json::Error> {
    let json = r#"{"bookingId": 5521, "totalCents": 45030, "type": "host"}"#;

    let payout: Payout = serde_json::from_str(json)?;
    println!("{payout:?}");
    println!("{}", serde_json::to_string(&payout)?);
    Ok(())
}
$ cargo run
Payout { booking_id: 5521, total_cents: 45030, kind: "host" }
{"bookingId":5521,"totalCents":45030,"type":"host"}

The Rust code uses payout.booking_id and payout.kind; the JSON keeps the API’s names. The rename lives in one place, on the struct.

5. Optional fields and defaults

An Option field is None when the key is missing or null. #[serde(default)] fills a missing field with its type’s default (0, an empty Vec, an empty String), for fields that are optional but not “unknown”.

src/main.rs
use serde::Deserialize;

#[derive(Deserialize)]
struct Review {
    booking_id: u64,
    score: u8,
    comment: Option<String>,
    #[serde(default)]
    tags: Vec<String>,
}

fn main() -> Result<(), serde_json::Error> {
    let full = r#"{"booking_id": 5521, "score": 5, "comment": "Lovely flat", "tags": ["clean"]}"#;
    let bare = r#"{"booking_id": 5530, "score": 4, "comment": null}"#;

    for json in [full, bare] {
        let r: Review = serde_json::from_str(json)?;
        println!(
            "#{} scored {}, comment {:?}, tags {:?}",
            r.booking_id, r.score, r.comment, r.tags
        );
    }
    Ok(())
}
$ cargo run
#5521 scored 5, comment Some("Lovely flat"), tags ["clean"]
#5530 scored 4, comment None, tags []

The rule of thumb: Option when “not given” means something different from any real value; default when it does not.

6. Enums as strings, and nested data

A field-less enum is written as its variant name. rename_all = "lowercase" makes Status::Confirmed read and write as "confirmed", and any other string is an error, like a Laravel Rule::in(…). A Vec of structs is a JSON array of objects, so a paginated API response is just two structs:

src/main.rs
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Status {
    Pending,
    Confirmed,
    Cancelled,
}

#[derive(Deserialize)]
struct Booking {
    id: u64,
    status: Status,
}

#[derive(Deserialize)]
struct Page {
    data: Vec<Booking>,
    total: u64,
}

fn main() {
    let good = r#"{"data": [{"id": 1, "status": "confirmed"}, {"id": 2, "status": "pending"}], "total": 41}"#;
    let bad = r#"{"data": [{"id": 3, "status": "refunded"}], "total": 41}"#;

    for json in [good, bad] {
        match serde_json::from_str::<Page>(json) {
            Ok(page) => {
                println!("{} of {}:", page.data.len(), page.total);
                for booking in &page.data {
                    println!("  #{} {:?}", booking.id, booking.status);
                }
            }
            Err(error) => println!("rejected: {error}"),
        }
    }
}
$ cargo run
2 of 41:
  #1 Confirmed
  #2 Pending
rejected: unknown variant `refunded`, expected one of `pending`, `confirmed`, `cancelled` at line 1 column 40

The error names the unknown variant and lists the accepted ones. Cancelled is never constructed by this program, yet there is no dead-code warning: deriving Deserialize counts as using every variant, because JSON may contain any of them.

7. serde_json::Value: when the shape is not known

The {…} context at the end of a Laravel log line has a different shape for every message. For that, serde_json::Value holds any JSON, like the result of json_decode($text, true). You read it with ["key"] and convert with as_u64(), as_str() and friends, each returning an Option:

src/main.rs
use serde_json::Value;

fn main() {
    let line = r#"[2026-11-30 09:14:27] production.WARNING: Stripe webhook retried {"event":"evt_1QX2","attempt":2}"#;

    let Some((_, context)) = line.split_once(" {") else {
        println!("no context");
        return;
    };
    let json = format!("{{{context}");

    match serde_json::from_str::<Value>(&json) {
        Ok(value) => {
            let event = value["event"].as_str().unwrap_or("?");
            let attempt = value["attempt"].as_u64().unwrap_or(0);
            let missing = value["booking"].as_u64();
            println!("event {event}, attempt {attempt}, booking {missing:?}");
        }
        Err(error) => println!("context is not JSON: {error}"),
    }
}
$ cargo run
event evt_1QX2, attempt 2, booking None

split_once(" {") drops the { it splits on, so format!("{{{context}") puts it back: {{ is how you write a literal { in a format string, then {context} is the variable.

value["booking"] on a key that is not there gives Value::Null instead of panicking, so as_u64() is None. Prefer a struct whenever you know the shape; Value is for the parts you do not.

Coming from PHP

PHP’s JSON functions are untyped, and by default they fail quietly:

json.php
<?php

$booking = json_decode('{"id": 5521, "guest": "Lina", "nights": "three"}', true);
$nights = $booking['nights'];                   // "three": nothing checked it

$broken = json_decode('{"id": 5521, "guest": ');  // null, and no error unless you ask
echo json_last_error_msg();                      // "Syntax error"

$strict = json_decode($input, true, 512, JSON_THROW_ON_ERROR);   // throws instead

Laravel’s Form Requests and API Resources are the layer that adds types and validation on top. With serde, the struct is that layer: one definition gives you the parser, the validation of types and required fields, and the serialiser, all checked at compile time.

PracticeThe serde guide, and parse a real log context

Read the Attributes page of the serde guide, to know what exists. You will look things up there for the rest of the course.

Exercise: the exception class

Laravel writes an exception into the context as one string: {"exception":"[object] (Illuminate\\Database\\QueryException(code: 40001): …"}. Write fn exception_class(line: &str) -> Option<String> that returns Illuminate\Database\QueryException for such a line and None for a line without an exception. Use a struct with one field exception: String rather than Value, and ? on every Option. (serde_json::from_str(…).ok() turns the Result into an Option, dropping the error.)

Show the solution
src/main.rs
use serde::Deserialize;

#[derive(Deserialize)]
struct Context {
    exception: String,
}

fn exception_class(line: &str) -> Option<String> {
    let (_, rest) = line.split_once(" {")?;
    let context: Context = serde_json::from_str(&format!("{{{rest}")).ok()?;
    // "[object] (Illuminate\Database\QueryException(code: 40001): SQLSTATE…"
    let after = context.exception.strip_prefix("[object] (")?;
    let (class, _) = after.split_once("(code:")?;
    Some(class.to_string())
}

fn main() {
    let deadlock = r#"[2026-11-30 09:41:03] production.ERROR: Deadlock found {"exception":"[object] (Illuminate\\Database\\QueryException(code: 40001): SQLSTATE[40001] at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:825)"}"#;
    let info = r#"[2026-11-30 09:41:04] production.INFO: Booking confirmed {"booking":5521}"#;

    println!("{:?}", exception_class(deadlock));
    println!("{:?}", exception_class(info));
}
$ cargo run
Some("Illuminate\\Database\\QueryException")
None

{:?} on the Option<String> shows each backslash doubled, because debug output escapes them; the String itself holds single backslashes, as the JSON decoder unescaped them. For the info line, the context has no exception key, so from_str fails and .ok()? returns None.

Remember

  • Describe the data as a struct and derive Serialize / Deserialize: the type is the validation.
  • Option for fields that may be missing, rename_all for an API’s naming, Value only for shapes you cannot know.

Tomorrow: the csv crate. A huge survey export read row by row into these same structs, with bad rows reported instead of stopping the run.