将字符串向量转换为深度嵌套的JSON对象

时间:2017-10-14 07:40:14

标签: arrays json rust

我试图使用the json crate从字符串向量中获取深层嵌套的JSON对象:

fn main() {   
    let my_vec = ["foo", "bar", "baz", "foobar", "barfoo"];
    let mut curr_obj = object!();
    for i in 0..my_vec.len() {
        let name = my_vec[i];
        curr_obj = addObj(curr_obj, name);   
    }
}

fn addObj(mut obj: json::JsonValue, name: &str) -> json::JsonValue {
    obj[name] = json::JsonValue::new_object();
    let retob = obj[name];
    retob.to_owned() // is empty but should be obj["foo"] = object!();
}

这里的对象是空的。我想要的输出如下:

{
  "foo": {
    "bar": {
      "baz": {
        "foobar": {
          "barfoo": {}
        }
      }
    }
  }
}

我收到错误

error[E0507]: cannot move out of indexed content
  --> src/main.rs:15:17
   |
15 |     let retob = obj[name];
   |                 ^^^^^^^^^
   |                 |
   |                 cannot move out of indexed content
   |                 help: consider using a reference instead: `&obj[name]`

2 个答案:

答案 0 :(得分:3)

可以用一点点魔法来完成。

fn main() {   
    let my_vec = ["foo","bar","baz","foobar","barfoo"];
    let mut curr_obj = object!();
    {
        let mut obj_ref = &mut curr_obj;
        for i in 0..my_vec.len() {
            let name = my_vec[i];
            obj_ref = &mut {obj_ref}[name]; // note the curly braces
        }
    }
    println!("{:?}", curr_obj);
}

移动可变参考而不是重新借用。

答案 1 :(得分:1)

使用迭代器方法要简单得多:

#[macro_use]
extern crate json;

fn main() {
    let my_vec = ["foo", "bar", "baz", "foobar", "barfoo"];

    let result = my_vec.iter().rev().fold(object!(), |object, name| {
        object!(name => object)
    });

    println!("{}", json::stringify_pretty(result, 2));
}

产地:

{
  "foo": {
    "bar": {
      "baz": {
        "foobar": {
          "barfoo": {}
        }
      }
    }
  }
}