2017-10-14 69 views
0

我試圖使用the json crate字符串矢量得到一個深度嵌套的JSON對象:字符串轉換的矢量到deply嵌套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]` 
+0

'addObj'不地道鏽的風格,應該snake_case:'add_obj'。 – Shepmaster

回答

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); 
} 

可變引用移動而不是被重新借出。

+0

我記得有類似的問題,但我現在找不到它。 – red75prime

+1

您可以添加更多關於大括號魔術的細節(或參考),以及移動和重新引用可變引用的區別嗎? – user4815162342

+0

我需要走。搜索所以重新借貸,有很好的描述。 – red75prime

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": {} 
     } 
     } 
    } 
    } 
}