How can I deserialize JSON with a top-level array using Serde?
Asked Answered
I

1

45

I have a some JSON data that is returned from a web service. The JSON is a top-level array:

[
    {
        "data": "value1"
    },
    {
        "data": "value2"
    },
    {
        "data": "value3"
    }
]

Using serde_derive to make structs I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array.

Am I missing something, or can Serde not deserialize top level-arrays?

Interosculate answered 18/6, 2017 at 0:13 Comment(0)
B
61

You can simply use a Vec:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    data: String,
}

fn main() -> Result<(), serde_json::Error> {
    let data = r#"[
        {
            "data": "value1"
        },
        {
            "data": "value2"
        },
        {
            "data": "value3"
        }
    ]"#;

    let datas: Vec<Foo> = serde_json::from_str(data)?;

    for data in datas.iter() {
        println!("{:#?}", data);
    }

    Ok(())
}

If you wish, you could also use transparent:

#[derive(Serialize, Deserialize, Debug)]
#[serde(transparent)]
struct Foos {
    foos: Vec<Foo>,
}

let foos: Foos = serde_json::from_str(data)?;

This allows to encapsulate your data with your type.

Breed answered 18/6, 2017 at 0:33 Comment(5)
What if the input JSON body is not an array? Is there any general way to handle it? Thansk!Anaerobe
@Anaerobe there is no more simple github.com/serde-rs/…Breed
Thank you, I just find the the answer in issue discussion, We can use let foos: serde_json::Value = serde_json::from_str(data)?;Anaerobe
But how do you parse this file efficiently if it's 10 GB size ?Belgrade
Why didn't I look this up 4 hours ago! Thank you!Clad

© 2022 - 2024 — McMap. All rights reserved.