about summary refs log tree commit diff
path: root/users/wpcarro/scratch/rust/json/src/main.rs
blob: e5f1078b5d01bb6497f851dd535329c1fadc1f0a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use serde_json::{json, Value};

// From the serde_json docs:
//
// > There are three common ways that you might find yourself needing to work with
// > JSON data in Rust.
// >
// > 1. As text data. An unprocessed string of JSON data that you receive on an
// >    HTTP endpoint, read from a file, or prepare to send to a remote server.
// > 2. As an untyped or loosely typed representation. Maybe you want to check
// >    that some JSON data is valid before passing it on, but without knowing
// >    the structure of what it contains. Or you want to do very basic
// >    manipulations like insert a key in a particular spot.
// > 3. As a strongly typed Rust data structure. When you expect all or most of
// >    your data to conform to a particular structure and want to get real work
// >    done without JSON’s loosey-goosey nature tripping you up.
//
// So let's take a look at all three...

// 1) Reading/writing from/to plain text.
//    TL;DR:
//    - read:  serde_json::from_str(data)
//    - write: x.to_string()
fn one() {
    let data = json!({
        "fname": "William",
        "lname": "Carroll",
        "age": 30,
    })
    .to_string();

    println!("result: {:?}", data);
}

// 2) Parse into a loosely typed representation; mutate it; serialize it back.
//    TL;DR:
//    - read:  serde_json::from_str(data)
//    - write: x.to_string()
fn two() {
    let data = r#"{"fname":"William","lname":"Carroll","age":30}"#;

    let mut parsed: Value = serde_json::from_str(data).unwrap();
    parsed["fname"] = json!("Norm");
    parsed["lname"] = json!("Macdonald");
    parsed["age"] = json!(61);

    let result = parsed.to_string();
    println!("result: {:?}", result);
}

fn main() {
    two()
}