Rust
JSON
Read and write JSON with serde_json.
JSON
serde_json works in both directions: to_string / to_string_pretty write, from_str reads. Reading can fail (missing field, wrong type), so it returns a Result:
let k = Kitap { ad: "Dune".into(), yil: 1965 };
let metin = serde_json::to_string(&k)?;
let geri: Kitap = serde_json::from_str(&metin)?;
// for JSON of unknown type
let v: serde_json::Value = serde_json::from_str(r#"{"a":[1,2]}"#)?;
println!("{}", v["a"][1]); // 2
r#"..."# is a raw string; quotes inside it don't need escaping.
A simple reader
Writing a full JSON parser is a big job; but splitting a flat (non-nested) object is enough to understand what from_str does:
fn duz_oku(json: &str) -> BTreeMap<String, String> {
json.trim()
.trim_start_matches('{')
.trim_end_matches('}')
.split(',')
.filter_map(|cift| cift.split_once(':'))
.map(|(a, d)| (a.trim().trim_matches('"').to_string(),
d.trim().trim_matches('"').to_string()))
.collect()
}
This reader doesn't handle commas inside strings or nested objects; in a real project always use serde_json.
Exercise Read a flat object
Write the duz_oku function above. Read the text {"ad":"Ece","yas":30} and print the result with {:?}.
Show example solution
use std::collections::BTreeMap;
fn duz_oku(json: &str) -> BTreeMap<String, String> {
json.trim()
.trim_start_matches('{')
.trim_end_matches('}')
.split(',')
.filter_map(|cift| cift.split_once(':'))
.map(|(a, d)| (a.trim().trim_matches('"').to_string(), d.trim().trim_matches('"').to_string()))
.collect()
}
fn main() {
println!("{:?}", duz_oku(r#"{"ad":"Ece","yas":30}"#));
}
Test yourself
-
What does <code>from_str::<Kitap>(r#"{"ad":"Dune"}"#)</code> return? (yil missing)
- Ok, yil = 0
- Panic
- Ok, yil = None
- Err: missing field `yil`
Show answer
Err: missing field `yil` — A missing field is an error by default. Optional fields are marked with Option or #[serde(default)].
-
Read from JSON
let geri: Kitap = serde_json::____(&metin)?;
Show answer
let geri: Kitap = serde_json::from_str(&metin)?;
-
Function and job
- to_string
- Single-line JSON
- to_string_pretty
- Indented JSON
- from_str
- JSON → type
- Value
- Untyped JSON
Next lesson: Field rename