rust 如何解析JSON文件?

hujrc8aj  于 2022-11-12  发布在  其他
关注(0)|答案(6)|浏览(320)

到目前为止,我的目标是在Rust中解析JSON数据:

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"
    ]
}

我的主要目标是获得这样的JSON数据,并从中解析出一个键,比如Age。

kmpatx3s

kmpatx3s1#

Serde是首选的JSON序列化提供程序。您可以使用read the JSON text from a file a number of ways。一旦将其作为字符串,请使用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可以用于JSON以外的格式,并且可以序列化和反序列化为自定义结构体,而不是任意集合:

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)
}

有关详细信息,请查看Serde website

yhived7q

yhived7q2#

由Rust社区的许多乐于助人的成员解决:

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

fn main() {
    let mut file = File::open("text.json").unwrap();
    let mut data = String::new();
    file.read_to_string(&mut data).unwrap();

    let json = Json::from_str(&data).unwrap();
    println!("{}", json.find_path(&["Address", "Street"]).unwrap());
}
roejwanj

roejwanj3#

serde_json::de::from_reader文档中有一个简单而完整的例子,说明如何从文件中读取JSON。
以下是的简短片段:

  • 阅读文件
  • 将其内容解析为JSON
  • 并提取具有所需关键字的字段

享受:

let file = fs::File::open("text.json")
    .expect("file should open read only");
let json: serde_json::Value = serde_json::from_reader(file)
    .expect("file should be proper JSON");
let first_name = json.get("FirstName")
    .expect("file should have FirstName key");
snvhrwxg

snvhrwxg4#

对已接受的答案投了赞成票(因为这很有帮助),但只是添加了我的答案,使用了@FrickeFresh引用的广泛使用的serde_json crate
假设您的foo.json

{
    "name": "Jane",
    "age": 11
}

实现类似于

extern crate serde;
extern crate json_serde;

# [macro_use] extern crate json_derive;

use std::fs::File;
use std::io::Read;

# [derive(Serialize, Deserialize)]

struct Foo {
    name: String,
    age: u32,
}

fn main() {
   let mut file = File::open("foo.json").unwrap();
   let mut buff = String::new();
   file.read_to_string(&mut buff).unwrap();

   let foo: Foo = serde_json::from_str(&buff).unwrap();
   println!("Name: {}", foo.name);
}
0h4hbjxa

0h4hbjxa5#

你可以将这个功能提取到一个实用程序中。根据他们的文档,这可能是一个有效的软件

use std::{
    fs::File,
    io::BufReader,
    path::Path,
    error::Error
};

use serde_json::Value;

fn read_payload_from_file<P: AsRef<Path>>(path: P) -> Result<Value, Box<dyn Error>> {
    // Open file in RO mode with buffer
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file
    let u = serde_json::from_reader(reader)?;

    Ok(u)
}

fn main() {
  let payload: Value = 
     read_payload_from_file("./config/payload.json").unwrap();
}
u3r8eeie

u3r8eeie6#

Rust附带了一个优雅的native-jsonwsd::json)crate,它用Rust声明了本机JSON对象,以及对成员的本机访问。

原生json方式

use wsd::json::*;

fn main() {
    // Declare as native JSON object
    let mut john = json!{
        name: "John Doe",
        age: 43,
        phones: [
            "+44 1234567",
            "+44 2345678"
        ]
    };

    // Native access to member
    john.age += 1;

    println!("first phone number: {}", john.phones[0]);

    // Convert to a string of JSON and print it out
    println!("{}", stringify(&john, 4));
}

serde_json方式

use serde_json::json;

fn main() {
    // The type of `john` is `serde_json::Value`
    let john = json!({
        "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678"
        ]
    });

    println!("first phone number: {}", john["phones"][0]);

    // Convert to a string of JSON and print it out
    println!("{}", john.to_string());
}

相关问题