How do I parse a JSON File?

后端 未结 4 1557
梦如初夏
梦如初夏 2020-12-13 12:28

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:         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 13:10

    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"
    

    You could even use something like serde_json::from_reader to read directly from an opened 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,
    }
    
    #[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.

提交回复
热议问题