DEV Community

BC
BC

Posted on

Day15:Load and Dump JSON - 100DayOfRust

We will use serde and serde_json crate to parse string to object and dump object to json string.

This code contains:

  • Read json string from file and parse string to object
  • Use json! macro to create Value object and use .to_string() function to dump object to string
  • Use Serialize and Deserialize trait for self-defined struct so we can dump it to string
  • Use serde_json::to_string and serde_json::to_string_pretty to dump object to string

First let's create a config.json file for test reading, put it in the same level as the Cargo.toml, like this:

proj
|-- Cargo.toml
|-- config.json
|-- src

In config.json, put some sample json string:

{
    "debug": true,
    "name": "serdetest"
}
Enter fullscreen mode Exit fullscreen mode

And in Cargo.toml file:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.42"
Enter fullscreen mode Exit fullscreen mode

Make sure features = ["derive"] exists [1], otherwise later in our code, #[derive(Serialize)] won't work.

Code in main.rs:

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use std::fs;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    score: i32,
}


fn main() {
    // parse config file
    let path = concat!(env!("CARGO_MANIFEST_DIR"), "/config.json");
    let s = fs::read_to_string(path).unwrap();
    let cfg: Value = serde_json::from_str(&s).unwrap();
    println!("Config: debug {}", cfg["debug"]);

    // json! macro
    let bonus = 10;
    let result = json!({
        "name": "Bo",
        "score": 92 + bonus,
    });
    println!("JSON!: {}", result.to_string());
    println!("JSON! Pretty: {}", serde_json::to_string_pretty(&result).unwrap());

    // serde_json to_string and to_string_pertty
    let p = Person {name: "Bo".to_owned(), score: 92};
    let serialized = serde_json::to_string(&p).unwrap();
    println!("Person serialized: {}", serialized);

    let serialized_pretty = serde_json::to_string_pretty(&p).unwrap();
    println!("Person serialized pretty: {}", serialized_pretty);

}
Enter fullscreen mode Exit fullscreen mode

Result:

Config: debug true
JSON!: {"name":"Bo","score":102}
JSON! Pretty: {
  "name": "Bo",
  "score": 102
}
Person serialized: {"name":"Bo","score":92}
Person serialized pretty: {
  "name": "Bo",
  "score": 92
}
Enter fullscreen mode Exit fullscreen mode

Reference

[1] https://serde.rs/derive.html

Top comments (0)