Sub topic 11
Working with untyped JSON using Value
This chapter assumes you can derive Serialize and Deserialize, call serde_json::from_str and to_string, and handle Result with ?. It also assumes you know what an enum with data looks like. The chapter covers serde_json::Value for JSON whose shape you do not know in advance. It also covers when to convert Value into typed structs.
Why an untyped representation exists
Derived structs are the default for good reasons. They check the shape of the input and give you named fields with real types. Sometimes you cannot write the struct:
- The input comes from a third-party API with a shape that varies.
- You are forwarding or patching JSON and only care about one key.
- You are writing a tool such as a linter or a diff viewer that must accept any JSON document.
- Part of a document (a
payloadfield) has a shape that depends on another field.
For these cases serde_json provides Value, an enum that can hold any JSON document:
pub enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}Value implements both Serialize and Deserialize. It is a type like any other, so you can deserialize into it, serialize from it, or use it as a field inside a derived struct.
Parsing and printing
Call from_str with Value as the target type. Indexing with a string or a number reads into the document. Printing a Value with {} writes compact JSON.
use serde_json::Value;
fn main() -> Result<(), serde_json::Error> {
let text = r#"{"name":"Ada","age":36,"tags":["math","code"],"address":null}"#;
let v: Value = serde_json::from_str(text)?;
println!("{}", v["name"]); // "Ada"
println!("{:?}", v["name"].as_str()); // Some("Ada")
println!("{}", v["tags"][1]); // "code"
println!("{}", v["missing"]); // null
println!("{}", v["name"] == "Ada"); // true
Ok(())
}Note that v["name"] prints with quotes, because Display writes JSON, not the bare string. Use as_str() when you want the Rust &str.
Reading safely
Indexing never panics on reads. A missing key, an out-of-range array index, or indexing into a value of the wrong kind all return Value::Null. That is convenient, but it hides typos: v["nmae"] looks like a JSON null. When the difference between "absent" and "null" matters, use get, which returns Option<&Value>.
The as_* methods return Option and check the kind of value for you. These are the ones you will use most:
| Method | Returns | `Some` when the value is |
|---|---|---|
| `as_str()` | `Option<&str>` | a string |
| `as_bool()` | `Option<bool>` | a boolean |
| `as_i64()` | `Option<i64>` | a number that fits in `i64` |
| `as_u64()` | `Option<u64>` | a non-negative integer |
| `as_f64()` | `Option<f64>` | any number |
| `as_array()` | `Option<&Vec<Value>>` | an array |
| `as_object()` | `Option<&Map<String, Value>>` | an object |
| `is_null()` | `bool` | `null` |
For nested lookups, chain get calls or use pointer, which takes a JSON Pointer (RFC 6901) such as /tags/1.
use serde_json::{json, Value};
fn main() {
let v = json!({
"user": { "tags": ["math", "code"], "age": 36 },
"ratio": 1.5
});
let first = v
.get("user")
.and_then(|u| u.get("tags"))
.and_then(|t| t.get(0))
.and_then(Value::as_str);
println!("{first:?}"); // Some("math")
println!("{:?}", v.pointer("/user/tags/1")); // Some(String("code"))
println!("{:?}", v.pointer("/user/nope")); // None
println!("{:?}", v["user"]["age"].as_i64()); // Some(36)
println!("{:?}", v["ratio"].as_i64()); // None
println!("{:?}", v["ratio"].as_f64()); // Some(1.5)
println!("{:?}", v["user"]["age"].as_f64()); // Some(36.0)
}as_i64 returns None for 1.5. It does not truncate. A None from an as_* method means "wrong kind or does not fit", so handle it explicitly instead of calling unwrap.
Building values with json!
The json! macro writes JSON literals directly in Rust. You can interpolate any expression whose type implements Serialize.
use serde_json::json;
fn main() {
let name = "Ada";
let scores = vec![90, 85];
let doc = json!({
"user": name,
"scores": scores,
"active": true,
"extra": null
});
println!("{doc}");
// {"active":true,"extra":null,"scores":[90,85],"user":"Ada"}
}Notice the key order in the output. By default serde_json::Map is backed by a BTreeMap, so keys come out sorted alphabetically, not in insertion order. If you need to keep the order of the input, enable the preserve_order feature of serde_json in Cargo.toml.
Modifying a Value
Value supports mutation through IndexMut, get_mut, as_array_mut, and as_object_mut.
use serde_json::json;
fn main() {
let mut v = json!({ "count": 1, "list": [1, 2] });
v["count"] = json!(2); // replace an existing key
v["new"] = json!(true); // insert a new key
if let Some(list) = v["list"].as_array_mut() {
list.push(json!(3));
}
if let Some(obj) = v.as_object_mut() {
obj.remove("count");
}
println!("{v}"); // {"list":[1,2,3],"new":true}
}Assignment through an index has two behaviors that can surprise you:
- Assigning to a missing key on an object, or on a
Nullvalue, creates the key. ANullvalue is turned into an object first, sov["a"]["b"] = json!(1)works on an emptyNulland builds both levels. - Assigning through an index panics if the value is the wrong kind (for example a number indexed by a string) or if an array index is out of range.
Numbers
JSON has one number type, while Rust has many. serde_json::Number stores an unsigned integer, a signed integer, or a 64-bit float, depending on how the number was written in the input. Consequences:
1and1.0are differentNumbers.as_i64()succeeds on the first and fails on the second.- Integers beyond
u64ori64range are parsed asf64and may lose precision. Thearbitrary_precisionfeature keeps the original digits, at the cost of a different internal representation. - NaN and infinity cannot be represented.
json!(f64::NAN)producesnull, becauseNumber::from_f64returnsNonefor them.
Converting between Value and typed data
Value is also a bridge to typed code. serde_json::from_value turns a Value into any Deserialize type, and serde_json::to_value goes the other way.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[derive(Debug, Serialize, Deserialize)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug, Deserialize)]
struct Envelope {
kind: String,
payload: Value,
}
fn handle(env: Envelope) -> Result<(), serde_json::Error> {
match env.kind.as_str() {
"point" => {
let p: Point = serde_json::from_value(env.payload)?;
println!("point at {}, {}", p.x, p.y);
}
"text" => println!("text: {}", env.payload["body"]),
other => println!("unknown kind {other}"),
}
Ok(())
}
fn main() -> Result<(), serde_json::Error> {
let p: Point = serde_json::from_value(json!({ "x": 1, "y": 2 }))?;
println!("{p:?}"); // Point { x: 1, y: 2 }
println!("{}", serde_json::to_value(&p)?); // {"x":1,"y":2}
let env: Envelope =
serde_json::from_str(r#"{"kind":"point","payload":{"x":5,"y":6}}"#)?;
handle(env)?; // point at 5, 6
Ok(())
}The Envelope type is the hybrid pattern. The outer shape is typed and checked. The payload stays untyped until kind says which struct to use. This is often better than a single Value for the whole document, and it is an alternative to an adjacently tagged enum when the set of kinds is open-ended.
Errors from from_value differ from errors from from_str. There is no source text, so line() and column() on the error are 0. The message still names the expected and actual types, for example invalid type: string "x", expected i32.
Choosing between typed data and Value
| Concern | Derived type | `Value` |
|---|---|---|
| Validation | Wrong types and missing fields fail at parse time | Nothing is checked until you call `as_*` |
| Typos in key names | Compile error | Silent `Null` or `None` |
| Memory | Fields stored directly | Every string, array, and map allocates |
| Speed | One pass from text to struct | One pass to `Value`, then another conversion if you want a struct |
| Flexibility | Fixed shape | Any valid JSON |
Parsing into Value and then calling from_value does the work twice and loses line and column information in errors. If you know the full shape up front, deserialize directly into the struct with from_str.
Common mistakes
- Using
v["key"].as_str().unwrap()on external input. A missing key becomes a panic. Return an error or a default instead. - Expecting
Displayoutput to be the bare string.{}on a stringValueincludes the quotes. - Relying on key order from
json!orMapwithoutpreserve_order. - Treating
as_i64()as a conversion. It only succeeds when the stored number is already an integer in range. - Using
Valuefor a whole document when only one field is dynamic.
Exercise
Given let v: Value = serde_json::from_str(r#"{"a":{"b":[10,20]}}"#)?;, write an expression that returns Some(20) as an Option<i64> without any chance of a panic, and say what v["a"]["c"]["d"] evaluates to.
Show answer
v.pointer("/a/b/1").and_then(Value::as_i64) returns Some(20). Chained get calls (v.get("a").and_then(|a| a.get("b")).and_then(|b| b.get(1)).and_then(Value::as_i64)) work too. The expression v["a"]["c"]["d"] evaluates to Value::Null, because reading a missing key or indexing into Null returns Null instead of panicking.
Exercise
A service sends {"kind":"point","payload":{"x":1,"y":2}} and other kinds with different payloads. Which design avoids parsing the payload twice for the kinds you handle, and where do you convert the payload?
Show answer
Use a struct with kind: String and payload: serde_json::Value, deserialized directly with from_str. Then match on kind and call serde_json::from_value::<Point>(env.payload) only in the branch that needs a Point. Unknown kinds keep the payload as an untouched Value.