0
我跑過Rust的標準JSON庫http://doc.rust-lang.org/serialize/json/,無法弄清楚代表其中的節點是什麼。在Java中它是JsonNode
。 Rust在什麼地方?例如,如何在Rust中傳遞JsonNode
類型的參數?JSON在Rust中的JsonNode
我跑過Rust的標準JSON庫http://doc.rust-lang.org/serialize/json/,無法弄清楚代表其中的節點是什麼。在Java中它是JsonNode
。 Rust在什麼地方?例如,如何在Rust中傳遞JsonNode
類型的參數?JSON在Rust中的JsonNode
Rust的JSON的「DOM」由Json
enum定義。例如,這JSON對象:
{ "array": [1, 2, 3], "submap": { "bool": true, "string": "abcde" } }
由該表達在鏽表示:
macro_rules! tree_map {
($($k:expr -> $v:expr),*) => ({
let mut r = ::std::collections::TreeMap::new();
$(r.insert($k, $v);)*
r
})
}
let data = json::Object(tree_map! {
"array".to_string() -> json::List(vec![json::U64(1), json::U64(2), json::U64(3)]),
"submap".to_string() -> json::Object(tree_map! {
"bool".to_string() -> json::Boolean(true),
"string".to_string() -> json::String("abcde".to_string())
})
});
(嘗試here)
我使用自定義地圖建設宏因爲不幸鏽病標準圖書館不提供一個(但我希望)。
Json
只是一個普通的枚舉,所以你必須使用模式匹配從它提取值。 Object
包含TreeMap
一個實例,因此,你必須使用它的方法來檢查對象結構:
if let json::Object(ref m) = data {
if let Some(value) = m.find_with(|k| "submap".cmp(k)) {
println!("Found value at 'submap' key: {}", value);
} else {
println!("'submap' key does not exist");
}
} else {
println!("data is not an object")
}
更新
顯然,Json
提供了很多方便的方法,包括find()
,這將返回Option<&Json>
如果目標是具有相應密鑰的Object
:
if let Some(value) = data.find("submap") {
println!("Found value at 'submap' key: {}", value);
} else {
println!("'submap' key does not exist or data is not an Object");
}
感謝@ChrisMorgan的發現。
如何檢查「數據」是否具有某個關鍵字,如果有 - 檢索其值? – 2014-11-05 16:09:23
@AlexanderSupertramp,我已經更新了答案。然而,這只是一個普通的枚舉,所以如果你有這樣的問題,你最好閱讀[guide](http://doc.rust-lang.org/guide.html),它解釋瞭如何使用他們。 – 2014-11-05 18:18:53
@AlexanderSupertramp:['json.find(&String)'](http://doc.rust-lang.org/serialize/json/enum.Json.html#method.find) – 2014-11-05 20:55:58