Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize JSON that contains a string with more JSON?

Tags:

json

rust

serde

I have a JSON object that contains a string that itself is a JSON object. How can I deserialize it?

I'd like to be able to do something like:

#[derive(Deserialize)]
struct B {
    c: String,
    d: u32,
}

#[derive(Deserialize)]
struct Test {
    a: String,
    b: B,
}

let object: Test = serde_json::from_str(
    r#"
    {
        "a": "string",
        "b": "{\"c\":\"c_string\",\"d\":1234}"
    }
"#,
)
.unwrap();

But this panics with invalid type: string "{\"c\":\"c_string\",\"d\":1234}", expected struct B

like image 608
Nils André Avatar asked Sep 12 '25 17:09

Nils André


1 Answers

You can use the serde_with crate with json::nested:

#[derive(Deserialize)]
struct Test {
    a: String,
    #[serde(with = "serde_with::json::nested")]
    b: B,
}
like image 159
Nils André Avatar answered Sep 14 '25 11:09

Nils André