0

我正在尝试解析一个输出如下输出的 JSON API:

{
  "message": "success", 
  "number": 6, 
  "people": [
    {
      "craft": "ISS", 
      "name": "Gennady Padalka"
    }, 
    {
      "craft": "ISS", 
      "name": "Mikhail Kornienko"
    }, 
    {
      "craft": "ISS", 
      "name": "Scott Kelly"
    }, 
    {
      "craft": "ISS", 
      "name": "Oleg Kononenko"
    }, 
    {
      "craft": "ISS", 
      "name": "Kimiya Yui"
    }, 
    {
      "craft": "ISS", 
      "name": "Kjell Lindgren"
    }
  ]
}

来源:http ://api.open-notify.org/astros.json

我为此使用了serde,并且到目前为止已经设法提出了以下代码:

extern crate curl;
extern crate serde_json;

use curl::http;
use std::str;
use serde_json::{from_str};

fn main() {
    // Fetch the data
    let response = http::handle()
       .get("http://api.open-notify.org/astros.json")
       .exec().unwrap();

     // Get the raw UTF-8 bytes
     let raw_bytes = response.get_body();
     // Convert them to a &str
     let string_body: &str = str::from_utf8(&raw_bytes).unwrap();

     // Get the JSON into a 'Value' Rust type
     let json: serde_json::Value = serde_json::from_str(&string_body).unwrap();

     // Get the number of people in space
     let num_of_ppl: i64 = json.find_path(&["number"]).unwrap().as_i64().unwrap();
     println!("There are {} people on the ISS at the moment, they are: ", num_of_ppl);

     // Get the astronauts
     // Returns a 'Value' vector of people
     let ppl_value_space = json.find_path(&["people"]).unwrap();
     println!("{:?}", ppl_value_space);
}

现在,ppl_value_space正如预期的那样,得到我这个:

[{"craft":"ISS","name":"Gennady Padalka"}, {"craft":"ISS","name":"Mikhail Kornienko"}, {"craft":"ISS","name":"Scott Kelly"}, {"craft":"ISS","name":"Oleg Kononenko"}, {"craft":"ISS","name":"Kimiya Yui"}, {"craft":"ISS","name":"Kjell Lindgren"}]

但是,我想找到"name"关键,因为基本上有类似的东西:

[{"name":"Gennady Padalka"}, {"name":"Mikhail Kornienko"}, {"name":"Scott Kelly"}, {"name":"Oleg Kononenko"}, {"name":"Kimiya Yui"}, {"name":"Kjell Lindgren"}]

以便能够仅获取当前在太空中的宇航员的姓名。

我如何得到"name"inside "people",没有"craft"?

试着name喜欢这样:

ppl_value_space[0].find_path(&["name"]).unwrap();

但它以恐慌结束,这基本上意味着关键是None,因为我unwrap()Option<T>.

4

1 回答 1

2

这对我有用:

if let &Value::Array(ref people) = ppl_value_space {
    let names = people.iter().filter_map(|person| person.find_path(&["name"]));
    for name in names {
        println!("{:?}", name);
    }
}

由于 aserde_json::Value是一个enum,它可以是许多不同类型的值。数组只是其中之一,它可以是字符串或数字等其他东西。我们希望它是一个数组,但 Rust 迫使我们考虑其他情况。

Value::Array在这种情况下,我们使用if-let语句忽略除 a 之外的所有类型。当条件为真时,我们将获得对包含数组的引用。

我们遍历数组中的每一项并在其中找到名称对象。filter_map用于忽略None值,但您可能想做一些不同的事情。

每个值都被打印出来,但您也可以将collect它们转换成新的Vec或更令人兴奋的东西。

于 2015-08-09T21:52:12.277 回答