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"内を取得するにはどうすればよいですか?"people""craft"

私はそうしようとしましnameた:

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

しかし、それはパニックで終わります。これは基本的に、キーがNoneunwrap()あることを意味しますOption<T>

4

1 に答える 1