2014-11-05 48 views

回答

4

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的发现。

+0

如何检查“数据”是否具有某个关键字,如果有 - 检索其值? – 2014-11-05 16:09:23

+0

@AlexanderSupertramp,我已经更新了答案。然而,这只是一个普通的枚举,所以如果你有这样的问题,你最好阅读[guide](http://doc.rust-lang.org/guide.html),它解释了如何使用他们。 – 2014-11-05 18:18:53

+1

@AlexanderSupertramp:['json.find(&String)'](http://doc.rust-lang.org/serialize/json/enum.Json.html#method.find) – 2014-11-05 20:55:58