CodeBlanks Logo Icon CodeBlanks

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.

Practice Read a flat object

Write the duz_oku function above. Read the text {"ad":"Ece","yas":30} and print the result with {:?}.

Starter code

main.rs
use std::collections::BTreeMap;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
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}"#));
}

Expected output

{"ad": "Ece", "yas": "30"}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>from_str::&lt;Kitap&gt;(r#"{"ad":"Dune"}"#)</code> return? (yil missing)

  • Ok, yil = 0
  • Panic
  • Ok, yil = None
  • Err: missing field `yil` Correct answer

Explanation: A missing field is an error by default. Optional fields are marked with Option or #[serde(default)].

2 Read from JSON

Question
let geri: Kitap = serde_json::____(&metin)?;
Answer
let geri: Kitap = serde_json::from_str(&metin)?;

Explanation: from_str converts JSON text into the target type.

3 Function and job

Term Meaning
to_string Single-line JSON
to_string_pretty Indented JSON
from_str JSON → type
Value Untyped JSON

All lessons in Intermediate