7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

目的

serde_json::Valueの値を色々と加工してみたくなったので試してみました。

プログラム

Cargo.toml
[package]
name = "json"
version = "0.1.0"
edition = "2018"

[dependencies]
serde_json = "*"
main.rs
#[macro_use]
extern crate serde_json;

fn main() {
    // 値の変更
    let mut p = json!({"a": 1});
    *p.get_mut("a").unwrap() = serde_json::to_value(p["a"].as_i64().unwrap() * 2).unwrap();
    assert_eq!(p, json!({"a": 2}));

    // 配列に追加
    let mut p = json!([]);
    let a = json!({"a": 1});
    let b = json!({"b": 2});
    p.as_array_mut().unwrap().push(a);
    p.as_array_mut().unwrap().push(b);
    assert_eq!(p, json!([{"a": 1}, {"b": 2}]));

    // 属性を追加
    let mut p = json!({});
    p.as_object_mut().unwrap().insert("a".to_string(), serde_json::to_value(1).unwrap());
    p.as_object_mut().unwrap().insert("b".to_string(), serde_json::to_value(2).unwrap());
    assert_eq!(p, json!({"a": 1, "b": 2}));

    // ループで値変更
    let mut p = json!([{"value": 1}, {"value": 2}]);
    for item in p.as_array_mut().unwrap_or(&mut vec![]) {
        *item.get_mut("value").unwrap() = serde_json::to_value(item["value"].as_i64().unwrap() * 2).unwrap();
    }
    assert_eq!(p, json!([{"value": 2}, {"value": 4}]));
}

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?