Sub topic 11
Working with untyped JSON using Value
Sometimes you can't write a struct for the JSON you receive. The shape may vary, or you may only need one field from a large document. serde_json::Value handles these cases. It is an enum that can hold any JSON document.
This chapter assumes you can derive Serialize and Deserialize, and that you know serde_json::from_str and the ? operator.
What Value is
Value has one variant for each JSON type:
| Variant | JSON it holds |
|---|---|
| `Null` | `null` |
| `Bool(bool)` | `true` or `false` |
| `Number(Number)` | any number |
| `String(String)` | a string |
| `Array(Vec<Value>)` | an array |
| `Object(Map<String, Value>)` | an object |
Value implements both Serialize and Deserialize. You can therefore parse into it with the same functions you use for your own structs.
Reading and editing
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde_json::{json, Value};
fn main() -> Result<(), serde_json::Error> {
let text = r#"{"name":"Ada","age":36,"langs":["rust","c"]}"#;
let mut v: Value = serde_json::from_str(text)?;
println!("{}", v["name"]); // "Ada"
println!("{}", v["langs"][1]); // "c"
println!("{}", v["missing"]); // null
let age = v.get("age").and_then(Value::as_i64);
println!("{age:?}"); // Some(36)
println!("{:?}", v.pointer("/langs/0")); // Some(String("rust"))
v["age"] = json!(37);
v["email"] = json!("[email protected]");
println!("{v}");
Ok(())
}The last line prints {"age":37,"email":"[email protected]","langs":["rust","c"],"name":"Ada"}. By default, serde_json stores object keys in sorted order. Enable the preserve_order feature if you need to keep the input order.
The example uses these tools:
- Indexing with
v["key"]orv[0]is short. It never panics on a read. A missing key or a wrong type givesValue::Null. getreturns anOption<&Value>, so you can tell a missing key from a realnull.as_i64,as_str,as_bool,as_array,as_objectreturnOption. They giveNonewhen the variant doesn't match.pointertakes a JSON Pointer such as/langs/0and reaches deep values in one call.json!builds aValuefrom JSON-like syntax. You can embed Rust expressions in it.
Matching on variants
When the type of a value is unknown, match on the enum:
use serde_json::Value;
fn describe(v: &Value) -> String {
match v {
Value::Null => "nothing".to_string(),
Value::Bool(b) => format!("bool {b}"),
Value::Number(n) => format!("number {n}"),
Value::String(s) => format!("string {s}"),
Value::Array(items) => format!("array of {}", items.len()),
Value::Object(map) => format!("object with {} keys", map.len()),
}
}
fn main() {
println!("{}", describe(&serde_json::json!([1, 2, 3]))); // array of 3
}Moving between Value and your types
You can parse loosely first and commit to a struct once you know the shape. from_value and to_value convert without going through a string:
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
}
fn main() -> Result<(), serde_json::Error> {
let v = json!({ "id": 1, "name": "Ada" });
let user: User = serde_json::from_value(v)?;
println!("{user:?}"); // User { id: 1, name: "Ada" }
let back: Value = serde_json::to_value(&user)?;
println!("{back}"); // {"id":1,"name":"Ada"}
Ok(())
}A common pattern is to put a Value field inside a typed struct. The struct fixes the known fields, and the Value field carries a payload whose shape varies.
When to choose Value
Prefer typed structs when the shape is known. They validate input, document the data, and catch errors at the boundary. Use Value for exploratory scripts, pass-through data you don't inspect, and fields whose shape depends on other data.
Exercise
Given let v: Value = serde_json::from_str(r#"{"a":null}"#)?;, how do v["a"] and v["b"] differ from v.get("a") and v.get("b")?
Show answer
Indexing gives Value::Null for both keys, so you can't tell the real null from the missing key. v.get("a") returns Some(&Value::Null) and v.get("b") returns None, so get separates the two cases.