简体   繁体   中英

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.

My question is this, is this possible to de-serialize this JSON partially. By partially, I mean to some, but not all properties of the JSON response.

for Example, I have this 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?

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:

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.

See play.rust-lang.org example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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