Answer#
Parsing JSON in Rust is memory safe; the risks are about what the data means and how much it costs. A typed struct gives you the first for free (a missing field or a wrong type is an error), and a few attributes and limits cover the rest.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)] // a misspelt or smuggled field is an error, not silently ignored
struct Signup {
name: String,
age: u8,
}
fn main() {
let ok: Signup = serde_json::from_str(r#"{"name":"Ada","age":36}"#).unwrap();
println!("{} is {}", ok.name, ok.age);
println!("{:?}", serde_json::from_str::<Signup>(r#"{"name":"Ada","age":300}"#).map_err(|e| e.to_string()));
println!("{:?}", serde_json::from_str::<Signup>(r#"{"name":"Ada","age":36,"admin":true}"#).map_err(|e| e.to_string()));
// Very deep nesting is refused by serde_json's default recursion limit instead of exhausting the stack.
let deep = "[".repeat(200) + &"]".repeat(200);
println!("{:?}", serde_json::from_str::<serde_json::Value>(&deep).map_err(|e| e.to_string()));
}Ada is 36
Err("invalid value: integer `300`, expected u8 at line 1 column 23")
Err("unknown field `admin`, expected `name` or `age` at line 1 column 30")
Err("recursion limit exceeded at line 1 column 128")What the output shows: a number that does not fit u8 is an error, an unexpected field is an error, and a document nested 200 levels deep is refused by serde_json's recursion limit instead of crashing the program.
How to do it#
- Limit the body size before parsing (see the thread on limiting input size).
- Deserialize into a struct, not into
serde_json::Value, wherever you know the shape. - Add
#[serde(deny_unknown_fields)]to request structs. Do not use it on structs that must accept fields added by newer clients. - Choose narrow types (
u8, enums) so impossible values are rejected by the type. - Check business rules after parsing (ranges, lengths), preferably inside a checked newtype.
- Mark fields the client must not control with
#[serde(skip_deserializing)](see the thread on sensitive fields).
Common mistakes#
- Turning the recursion limit off (
disable_recursion_limit) on untrusted input. - Deserializing into a map or
Valueand then reading keys by hand, which loses the type checks. - Returning the parser's error text to the client in a way that reveals internal structure. A short generic message is enough; log the detail.
Related questions#
Does the same hold for other formats (TOML, YAML, XML)?#
The principles do: typed targets, size limits, and care with features that expand data. Check each parser's documentation for its limits and defaults.
Should I use serde_json::Value at all?#
For data whose shape you really do not know, such as pass-through documents. Check size and depth first, and convert to typed structs as soon as you can.
Sources#
- Serde documentation, container attributes: https://serde.rs/container-attrs.html
serde_jsondocumentation, recursion limit: https://docs.rs/serde_json/1.0.154/serde_json/struct.Deserializer.html#method.disable_recursion_limit- OWASP Input Validation Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html