读取然后用 rustc_serialize 修改 JSON

Reading then modifying JSON with rustc_serialize

假设我想用 {"foo": 14} 替换 {"foo": 13}。尝试次数:

extern crate rustc_serialize;
use rustc_serialize::json::Json;

fn main() {
    let data = Json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap();
    let mut obj = data.as_object().unwrap();
    let somenum: u64 = 14;
    obj.insert(String::from_str("foo"), Json::U64(somenum));

    for (key, value) in obj.iter() {
        println!("{}: {}", key, match *value {
            Json::U64(v) => format!("{} (u64)", v),
            Json::String(ref v) => format!("{} (string)", v),
            _ => format!("other")
        });
    }
}

错误:

src/main.rs:8:5: 8:8 error: cannot borrow immutable borrowed content `*obj` \
                            as mutable
src/main.rs:8     obj.insert(String::from_str("foo"), Json::U64(somenum));
                  ^~~

as_object returns Option<&Object>——一个不可变的引用。

要获取可变引用 (Option<&mut Object>),您必须使用 as_object_mut.