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相关问答推荐

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

从Json响应中为需要每个值的Post请求提取多个值

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

使用 jq 重新格式化 JSON 输出

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

如何编写 jolt 规范以将不同的对象转换为数组

使用 serde 和 csv crates 将嵌套的 json 对象序列化为 csv

转义 Haskell 记录的字段

嵌套 JSON 到 CSV(多级)

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

从 JSON 对象中删除键值对

Python - 如何将 JSON 文件转换为数据框

将带有数据和文件的 JSON 发布到 Web Api - jQuery / MVC

Spring Security 和 JSON 身份验证

jq:按属性分组和键

我如何反序列化以杰克逊为单位的时间戳?

play 2 JSON 格式中缺少的属性的默认值

在rails中将JSON字符串转换为JSON数组?