I have this so far in my goal to Parse this JSON data in Rust:

extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io::copy;
use std::io::stdout;

fn main() {
    let mut file = File::open("text.json").unwrap();
    let mut stdout = stdout();
    let mut str = &copy(&mut file, &mut stdout).unwrap().to_string();
    let data = Json::from_str(str).unwrap();
}

text.json

{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "PhoneNumbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}

What should be my next step into parsing it? My primary goal is to get JSON data like this, and parse a key from it, like Age.

推荐答案

Serde is the preferred JSON serialization provider. You can read the JSON text from a file a number of ways. Once you have it as a string, use serde_json::from_str:

fn main() {
    let the_file = r#"{
        "FirstName": "John",
        "LastName": "Doe",
        "Age": 43,
        "Address": {
            "Street": "Downing Street 10",
            "City": "London",
            "Country": "Great Britain"
        },
        "PhoneNumbers": [
            "+44 1234567",
            "+44 2345678"
        ]
    }"#;

    let json: serde_json::Value =
        serde_json::from_str(the_file).expect("JSON was not well-formatted");
}

Cargo .toml:

[dependencies]
serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0.48"

您甚至可以使用类似于serde_json::from_reader的东西直接从打开的File中读取.

Serde can be used for formats other than JSON and it can serialize and deserialize to a custom struct instead of an arbitrary collection:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Person {
    first_name: String,
    last_name: String,
    age: u8,
    address: Address,
    phone_numbers: Vec<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Address {
    street: String,
    city: String,
    country: String,
}

fn main() {
    let the_file = /* ... */;

    let person: Person = serde_json::from_str(the_file).expect("JSON was not well-formatted");
    println!("{:?}", person)
}

Check the Serde website for more details.

Json相关问答推荐

使用JQ从jsonl文件中删除具有匹配键/值的行

将=分隔值文件转换为:json文件

如何在 Apps 脚本中循环遍历 JSON 响应

从字节解码 JSON 数据,将 float 值更改为 int

如何将从嵌套 Select 返回的空值转换为空数组?

Servicestack 返回数组而不是带有数组的对象

如何用 Xidel 正确读取这个 JSON 文件?

如何对使用转换器的 Grails 服务进行单元测试?

谷歌浏览器不允许我放置断点

Spring MVC控制器中的JSON参数

使用 gson 反序列化对象的特定 JSON 字段

jQuery fullcalendar 发送自定义参数并使用 JSON 刷新日历

将文件发送到 Rails JSON API

如何将有向无环图 (DAG) 存储为 JSON?

确保数组中的项目属性在 Json Schema 中是唯一的?

Javascript:如何判断 AJAX 响应是否为 JSON

使用 JSON (iOS) 的 Cocoa 错误 3840

render :json => 'string here' 预期结果

在json中传递函数并执行

JSONP 请求错误处理