简体   繁体   English

使用 serde_json 部分解析 json

[英]Parsing json partially with serde_json

I am using serde_json in rust, and I am calling an api and get a very large json in return.我在 rust 中使用serde_json ,我正在调用 api 并得到一个非常大的 json 作为回报。

My question is this, is this possible to de-serialize this JSON partially.我的问题是,这是否可以部分反序列化这个 JSON。 By partially, I mean to some, but not all properties of the JSON response.部分是指 JSON 响应的一些属性,但不是所有属性。

for Example, I have this JSON:例如,我有这个 JSON:

 Object {
        "age_group": String(""),
        "amazon_product_url": String("https://www.amazon.com/dp/0063221489?tag=NYTBSREV-20"),
        "article_chapter_link": String(""),
        "asterisk": Number(0),
        "author": String("Jared Kushner"),
        "book_image": String("https://storage.googleapis.com/du-prd/books/images/9780063221482.jpg"),
        "book_image_height": Number(500),
        "book_image_width": Number(331),
        "book_review_link": String(""),
        "book_uri": String("nyt://book/e5ec4777-5f2f-5622-9288-9b1d96e8fe1d"),
        "buy_links": Array [
            Object {
                "name": String("Amazon"),
                "url": String("https://www.amazon.com/dp/0063221489?tag=NYTBSREV-20"),
            },
            Object {
                "name": String("Apple Books"),
                "url": String("https://goto.applebooks.apple/9780063221482?at=10lIEQ"),
            },
            Object {
                "name": String("Barnes and Noble"),
                "url": String("https://www.anrdoezrs.net/click-7990613-11819508?url=https%3A%2F%2Fwww.barnesandnoble.com%2Fw%2F%3Fean%3D9780063221482"),
            }
}

Then in this case, is it possible to just catch buy_links and amazon_product_url properties and never mind others?那么在这种情况下,是否有可能只捕获buy_linksamazon_product_url属性而不介意其他人?

If you only declare the fields you need, yes it is possible to only deserialize a subset of the data:如果您只声明您需要的字段,是的,可以只反序列化数据的子集:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn test(s: &str)
{
    let p: Point = serde_json::from_str(s).unwrap();
    println!("{:?}", p);
}

fn main()
{
    test("{\"x\":0,\"y\":3}");
    test("{\"x\":0,\"y\":2, \"z\": 4}");
}

Output: Output:

Point { x: 0, y: 3 }
Point { x: 0, y: 2 }

As you can see, the "z" field that is present in the second test is ignored.如您所见,第二个测试中存在的"z"字段被忽略了。

See play.rust-lang.org example.请参阅play.rust-lang.org示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM