29

I am totally new to rust and I am trying to find out how to I can doload an deserialize a arbitrary JSON structure from a URL endpoint.

The respective example on the reqwest README goes like this:

use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<HashMap<String, String>>()
        .await?;
        println!("{:#?}", resp);
    Ok(())
}

So in case of this example, the target structure – i.e. a HashMap Object with strings as keys and strings as values – is obviously known.

But what if I don't know what is the structure received on the request endpoint looks like?

1 Answer 1

34

You can use serde_json::Value.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<serde_json::Value>()
        .await?;
    println!("{:#?}", resp);
    Ok(())
}

You will have to add serde_json to your Cargo.toml file.

[dependencies]
...
serde_json = "1"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.