Say the provisioning API just handed you a subscriber record and your job is to read it in a Rust service. In Python or JavaScript you would parse it and start poking at keys. In Rust you will usually do one extra thing first: write down what the data looks like as a struct. That sounds like busywork, but it is the reason Rust code that reads JSON tends to break loudly at the edge of your program instead of quietly three functions later.
The tool almost everyone uses for this is serde, together with its JSON crate, serde_json. Below we take one subscriber payload and go through the things you will actually run into: camelCase keys, fields that are sometimes missing, lists, nested objects, JSON you don't know the shape of, error messages, and one long ID that JavaScript gets wrong. Every snippet here was compiled and run, and the output shown is what it printed.
If structs and Result are still new to you, spend an evening with a beginner-friendly Rust tutorial first. The rest of this page will make a lot more sense.
Add serde and serde_json to Cargo.toml
You need two crates. serde is the framework: it defines the Serialize and Deserialize traits and, with the derive feature, the macros that write the boring code for you. serde_json knows the actual JSON syntax. Forgetting the derive feature is the most common first error, and it shows up as "cannot find derive macro Deserialize".
[dependencies]
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"These are the versions the examples were built with. cargo add serde --features derive and cargo add serde_json write the same lines for you.
Read the payload into a struct
Here is the record we will use throughout. The API uses camelCase keys, while Rust fields are snake_case by convention. You could name your fields subscriberId and live with the compiler warnings, but one attribute on the struct is cleaner: #[serde(rename_all = "camelCase")] tells serde to map data_usage_gb to dataUsageGb for every field at once.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
subscriber_id: String,
name: String,
msisdn: String,
iccid: u64,
plan: String,
data_usage_gb: f64,
roaming: bool,
sectors: Vec<String>,
}
fn main() -> Result<(), serde_json::Error> {
let payload = r#"{
"subscriberId": "SUB-20417",
"name": "Ingrid Hallström",
"msisdn": "+46701234567",
"iccid": 8901240544102066246,
"plan": "Unlimited 5G",
"dataUsageGb": 42.7,
"roaming": false,
"sectors": ["STO-114", "STO-118", "UPP-022"]
}"#;
let sub: Subscriber = serde_json::from_str(payload)?;
println!("{} ({}) is on {}", sub.name, sub.subscriber_id, sub.plan);
println!("ICCID: {}", sub.iccid);
println!("Used {} GB across {} sectors", sub.data_usage_gb, sub.sectors.len());
Ok(())
}Ingrid Hallström (SUB-20417) is on Unlimited 5G ICCID: 8901240544102066246 Used 42.7 GB across 3 sectors
Notice that from_str needs to know what to build. The type annotation on let sub: Subscriber is what tells it. Leave it off and you get a "type annotations needed" error, which confuses everyone the first time. The raw string r#"..."# is only there so the quotes inside the JSON don't need escaping.
Keys that the struct doesn't mention are simply ignored, so an API that adds a field next month won't break you. If you would rather fail on surprises, put #[serde(deny_unknown_fields)] on the struct.
Writing the struct by hand is fine for eight fields. For a forty-field response, paste a sample into the JSON to Rust converter and skip writing the structs by hand, then adjust the types where you know better than the sample does.
Awkward key names, missing fields and defaults
Real payloads are messier than the first one. This record has a key called type, which is a Rust keyword, an email that is null, no addOns key at all, and a nested device object.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
subscriber_id: String,
name: String,
// "type" is a Rust keyword, so the field gets a different name
#[serde(rename = "type")]
line_type: String,
// may be missing, or may be null
email: Option<String>,
// missing means "no add-ons", not an error
#[serde(default)]
add_ons: Vec<String>,
device: Device,
}
#[derive(Debug, Deserialize)]
struct Device {
imei: String,
model: String,
}
fn main() -> Result<(), serde_json::Error> {
let payload = r#"{
"subscriberId": "SUB-20418",
"name": "Maeve Lindqvist",
"type": "postpaid",
"email": null,
"device": { "imei": "356938035643809", "model": "Pixel 9" }
}"#;
let sub: Subscriber = serde_json::from_str(payload)?;
println!("{sub:#?}");
Ok(())
}Subscriber {
subscriber_id: "SUB-20418",
name: "Maeve Lindqvist",
line_type: "postpaid",
email: None,
add_ons: [],
device: Device {
imei: "356938035643809",
model: "Pixel 9",
},
}Three tools, three jobs. #[serde(rename = "type")] maps one key to a field with a different name, and it wins over rename_all. Option<String> accepts a missing key or a null and gives you None either way. #[serde(default)] is for when "missing" should just mean "empty", so you get [] and never have to unwrap anything.
One thing that catches people: #[serde(default)] covers a missing key, not a null. Send "addOns": null and you get an "invalid type: null" error. If the API sends nulls, use Option.
The nested object needed nothing special. Device derives Deserialize too, so serde just reads it as another struct. If the attribute names start to blur together, the field attribute reference on serde.rs lists every one of them on a single page.
Arrays become Vec
You already saw sectors: Vec<String>. The same goes for a response that is a list at the top level: ask for a Vec of your struct and you can use iterators on it straight away.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
subscriber_id: String,
data_usage_gb: f64,
}
fn main() -> Result<(), serde_json::Error> {
let payload = r#"[
{ "subscriberId": "SUB-20417", "dataUsageGb": 42.7 },
{ "subscriberId": "SUB-20418", "dataUsageGb": 3.1 }
]"#;
let subs: Vec<Subscriber> = serde_json::from_str(payload)?;
let total: f64 = subs.iter().map(|s| s.data_usage_gb).sum();
println!("{} subscribers, {total:.1} GB in total", subs.len());
Ok(())
}2 subscribers, 45.8 GB in total
When you don't know the shape: serde_json::Value
Sometimes you only want two fields out of a big document, or the meta block changes from one vendor to the next. Parse into serde_json::Value and walk it like a tree.
use serde_json::Value;
fn main() -> Result<(), serde_json::Error> {
let payload = r#"{
"subscriberId": "SUB-20417",
"iccid": 8901240544102066246,
"sectors": ["STO-114", "STO-118"],
"meta": { "source": "hss-eu-north", "retries": 2 }
}"#;
let v: Value = serde_json::from_str(payload)?;
println!("first sector: {}", v["sectors"][0]);
println!("source: {}", v["meta"]["source"].as_str().unwrap_or("unknown"));
println!("iccid as u64: {:?}", v["iccid"].as_u64());
println!("missing key: {}", v["meta"]["region"]);
Ok(())
}first sector: "STO-114" source: hss-eu-north iccid as u64: Some(8901240544102066246) missing key: null
Two details worth knowing. Printing a Value directly prints JSON, which is why the first line has quotes and the second, read with as_str(), doesn't. And indexing a key that isn't there gives you null rather than a panic, so a typo in a key name fails silently. That is the trade you make for not writing a struct, and why Value is better as a starting point than a destination.
Writing JSON back out, compact or pretty
Going the other way is the same idea with Serialize. to_string gives you one line for the wire, to_string_pretty gives you something you can read in a log.
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
subscriber_id: String,
name: String,
iccid: u64,
roaming: bool,
sectors: Vec<String>,
}
fn main() -> Result<(), serde_json::Error> {
let sub = Subscriber {
subscriber_id: "SUB-20417".to_string(),
name: "Ingrid Hallström".to_string(),
iccid: 8901240544102066246,
roaming: false,
sectors: vec!["STO-114".into(), "STO-118".into()],
};
println!("{}", serde_json::to_string(&sub)?);
println!("{}", serde_json::to_string_pretty(&sub)?);
Ok(())
}{"subscriberId":"SUB-20417","name":"Ingrid Hallström","iccid":8901240544102066246,"roaming":false,"sectors":["STO-114","STO-118"]}
{
"subscriberId": "SUB-20417",
"name": "Ingrid Hallström",
"iccid": 8901240544102066246,
"roaming": false,
"sectors": [
"STO-114",
"STO-118"
]
}The same rename_all works in this direction too, so the keys come out camelCase again. If you want to check output from another service by eye, the JSON formatter will indent a minified response for you.
Errors, and what they actually say
So far main has returned Result and every parse ended in ?, which hands any error straight up to the caller. The error handling chapter of the Rust Book explains that operator properly. What matters here is how readable serde's errors are. Here are the two you will see most, a string where a number belongs and a key that isn't there:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Usage {
subscriber_id: String,
data_usage_gb: f64,
}
fn main() {
// a string where a number should be
let wrong_type = r#"{ "subscriberId": "SUB-20417", "dataUsageGb": "42.7" }"#;
// a required field is missing
let missing = r#"{ "subscriberId": "SUB-20417" }"#;
for payload in [wrong_type, missing] {
match serde_json::from_str::<Usage>(payload) {
Ok(u) => println!("parsed: {u:?}"),
Err(e) => println!("error: {e}"),
}
}
}error: invalid type: string "42.7", expected f64 at line 1 column 52 error: missing field `dataUsageGb` at line 1 column 31
The first one is the classic: some services send numbers as strings, and serde will not quietly convert them for you. That's a feature. Either fix the producer or make the field a String and parse it yourself. Notice the missing-field error uses the JSON name, dataUsageGb, not your Rust name, which is handy when you're comparing against the API docs.
When the JSON lives in a file, mix error types by returning Box<dyn Error>, so the file error and the parse error can both use ?:
use serde::Deserialize;
use std::error::Error;
use std::fs;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subscriber {
subscriber_id: String,
iccid: u64,
}
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("subscriber.json")?;
let sub: Subscriber = serde_json::from_str(&text)?;
println!("{} -> {}", sub.subscriber_id, sub.iccid);
Ok(())
}SUB-20417 -> 8901240544102066246
If the error points at a column and you can't see anything wrong, paste the document into the JSON validator. A stray trailing comma or a smart quote copied from a chat message is far easier to spot there than in a terminal.
The 19-digit ICCID that JavaScript gets wrong
You may have wondered why iccid was declared as u64 rather than a float. Here is the reason, side by side:
use serde::Deserialize;
#[derive(Deserialize)]
struct Sim {
iccid: u64,
}
#[derive(Deserialize)]
struct SimAsFloat {
iccid: f64,
}
fn main() -> Result<(), serde_json::Error> {
let payload = r#"{ "iccid": 8901240544102066246 }"#;
let exact: Sim = serde_json::from_str(payload)?;
let rounded: SimAsFloat = serde_json::from_str(payload)?;
println!("u64: {}", exact.iccid);
println!("f64: {}", rounded.iccid);
Ok(())
}u64: 8901240544102066246 f64: 8901240544102066000
That second line is exactly what JavaScript prints for JSON.parse('{"iccid": 8901240544102066246}').iccid. JavaScript has one number type, a 64-bit float, and it can only hold whole numbers exactly up to 9007199254740991. The JSON text itself was fine: RFC 8259 puts no limit on the size of a number and warns that software using doubles will lose precision past that point.
In Rust you pick the type, and a u64 holds anything up to 18446744073709551615, so the ICCID survives untouched. If you have to send it to a browser, consider sending it as a string. If an ID can be longer than 20 digits, use a String on the Rust side as well.
Frequently Asked Questions
How do I parse JSON in Rust?
Add serde with the derive feature and serde_json to Cargo.toml, describe the data as a struct with #[derive(Deserialize)], and call serde_json::from_str::<YourStruct>(text). If the text does not match the struct, you get a serde_json::Error that names the field plus the line and column. For a file, read it with std::fs::read_to_string first, or hand a reader to serde_json::from_reader.
What is the difference between serde and serde_json?
serde is the framework: it defines the Serialize and Deserialize traits and the derive macros that write the code for your structs. serde_json is a format crate that plugs into it and knows the actual JSON syntax. The same struct works with other formats too, such as quick-xml for XML or toml for TOML, which is why you add both crates.
How do I handle optional or missing fields with serde?
Make the field an Option<T>, and both a missing key and a null become None. If missing should mean an empty value rather than None, put #[serde(default)] on the field and serde fills in Default::default(), so an empty Vec, 0 or an empty String. With neither, a missing key is an error such as missing field `dataUsageGb`.
Why does my long ID stay exact in Rust but not in JavaScript?
Because in Rust you choose the number type, and u64 holds every whole number up to 18446744073709551615, so 8901240544102066246 is read exactly. JavaScript's JSON.parse turns every number into a 64-bit float, which only holds integers exactly up to 9007199254740991, so the same ICCID comes back as 8901240544102066000. Declare the field as f64 in Rust and you get the same rounding, so pick the integer type on purpose.
How do I parse JSON without knowing its structure in Rust?
Parse it into serde_json::Value, which can hold any JSON document. You index it like v["meta"]["source"] and read values with as_str(), as_u64() or as_f64(), and a missing key gives Value::Null instead of a panic. Once you know which part you care about, turn just that part into a struct with serde_json::from_value.
How do I pretty print JSON in Rust?
Call serde_json::to_string_pretty(&value) instead of serde_json::to_string. It works on any type that implements Serialize, including serde_json::Value, and indents with two spaces. If you want to write straight to a file, use serde_json::to_writer_pretty with the open file.
Where to go next
That covers what most services need: a struct per shape, rename_all for the casing, Option and default for the gaps, Value for the unknown parts, and integer types chosen on purpose. If you want more practice with derives and custom serializers, this Rust serde tutorial goes further with exercises.
And if the same subscriber shows up as XML from an older system, the structs barely change. The companion article on how to parse XML in Rust with quick-xml uses this exact record.