serde_json — the standard
Rust does not have JSON in the standard library. The de facto standard is serde_json, part of the serde framework — and it is not just popular, it is essentially universal. Every JSON tutorial, every library that touches JSON, every public API client uses it.
serde is a generic serialization framework. serde_json is its JSON backend. The split matters because the same #[derive(Serialize, Deserialize)] on your types works with serde_yaml, bincode, postcard, and dozens of other formats. Learn serde once, use it everywhere.
# Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Typed deserialization
The idiomatic Rust pattern: define a struct, derive Deserialize, parse into it. The compiler enforces that every field exists and has the right type.
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
id: u64,
name: String,
email: String,
age: Option<u32>,
}
let json = r#"{"id": 1, "name": "Ada", "email": "[email protected]"}"#;
let user: User = serde_json::from_str(json)?;
println!("{}", user.name); // AdaThe age field is Option<u32> because the input does not contain it. Required fields are non-Option types; optional fields are Option<T>. Missing required fields produce a deserialization error pointing at the line and column.
Renaming fields is one attribute:
#[derive(Deserialize)]
struct ApiResponse {
#[serde(rename = "user_id")]
id: u64,
#[serde(rename = "displayName")]
name: String,
}
// Or convert the whole struct's naming convention
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Config {
api_url: String, // matches "apiUrl" in JSON
max_retries: u8, // matches "maxRetries"
}#[serde(default)] on a field uses Default::default() when the JSON omits it — useful for backwards-compatible schema evolution.
Untyped (Value) deserialization
When you do not know the shape ahead of time — exploring an API, building a generic tool — parse into serde_json::Value:
use serde_json::Value;
let v: Value = serde_json::from_str(json)?;
// Index into objects and arrays
let name = &v["user"]["name"];
let first_tag = &v["tags"][0];
// Pattern match on type
match &v["age"] {
Value::Number(n) => println!("age: {}", n),
Value::Null => println!("no age"),
_ => println!("unexpected type"),
}Indexing on Value never panics — out-of-bounds or missing keys return Value::Null. Convert back to a typed Rust value with .as_str(), .as_u64(), .as_array(), etc., each returning Option<T>.
For production code, prefer typed deserialization wherever you can. Value is a slower runtime representation and pushes type errors from compile time to runtime. Use it for prototypes and admin tools.
Serializing back
use serde::Serialize;
#[derive(Serialize)]
struct Response {
id: u64,
name: String,
}
let r = Response { id: 1, name: "Ada".into() };
// Compact
let compact = serde_json::to_string(&r)?;
// → {"id":1,"name":"Ada"}
// Pretty-printed
let pretty = serde_json::to_string_pretty(&r)?;
// → {
// "id": 1,
// "name": "Ada"
// }Three attributes solve 90% of API-shaping needs: #[serde(skip_serializing_if = "Option::is_none")] omits null fields, #[serde(rename_all = "camelCase")] matches frontend conventions, #[serde(flatten)] spreads a nested struct's fields into the parent.
Error handling that does not lie
serde_json::Error implements std::error::Error and carries the line and column of the failure. Use the ? operator with proper error types — anyhow::Error for application code, your own enum for library code.
fn load_config(path: &str) -> Result<Config, Box<dyn std::error::Error>> {
let bytes = std::fs::read(path)?;
let config: Config = serde_json::from_slice(&bytes)?;
Ok(config)
}
// Error output includes:
// "invalid type: string "thirty", expected u32 at line 4 column 18"from_slice is faster than from_str because it avoids a UTF-8 validation pass — use it when reading from disk or network and the bytes are guaranteed valid by the source.
Streaming large documents
For NDJSON (newline-delimited JSON), one record per line, use a BufReader and parse each line:
use std::io::{BufRead, BufReader};
use std::fs::File;
let file = File::open("events.ndjson")?;
let reader = BufReader::new(file);
for line in reader.lines() {
let event: Event = serde_json::from_str(&line?)?;
process(event);
}For a single large JSON document, serde_json::Deserializer::from_reader exists but does not stream arrays element-by-element. For true streaming, look at json-event-parser (pull-based, no allocations) or struson (Java-style streaming reader port).
When serde_json is not fast enough
serde_json is fast — parses around 200-400 MB/s on a modern CPU. If you are bottlenecked on parsing (rare, usually you are bottlenecked on the network), simd-json uses SIMD instructions for roughly 4× the throughput.
# Cargo.toml
[dependencies]
simd-json = "0.13"
let mut bytes: Vec<u8> = std::fs::read("huge.json")?;
let value = simd_json::to_owned_value(&mut bytes)?;simd-json requires the input as a mutable byte vector because it writes back into the buffer during parsing — that is part of what makes it fast. Worth the API friction only when you have measured the bottleneck.
Gotchas Rust-specific
Floats lose precision. JSON numbers are deserialized as f64 by default. A 64-bit integer over 253 loses bits on the round-trip. Use serde_json::Number in your struct and inspect it with .as_u64() or .as_i64() for big-integer JSON, or use the arbitrary_precision feature flag.
Unknown fields are silently dropped. The default. Add #[serde(deny_unknown_fields)] to reject any JSON containing extra keys — useful for catching typos in config files.
HashMap key order is randomised. Serializing a HashMap produces non-deterministic output, which breaks file hashes and version-control diffs. Use BTreeMap when stable ordering matters.
Borrowed strings need lifetimes. &str in a struct ties the parsed value to the input buffer's lifetime. For most cases, just use String and let serde allocate. Worry about borrowed strings only when profiling says allocations are the bottleneck.
For more on the broader JSON ecosystem, see the JSON formatting guide for emit-side conventions and the JSON Schema validator for runtime contract checking.