Ask Your Question
1

How can you convert a reqwest::Response to JSON while also displaying the response text if an error occurs?

asked 2023-04-30 06:26:22 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-04-30 06:38:02 +0000

qstack gravatar image

To convert a reqwest::Response to JSON while also displaying the response text if an error occurs, you can use the following code:

use serde_json::Value;

fn main() -> Result<(), reqwest::Error> {
    let response = reqwest::get("https://jsonplaceholder.typicode.com/todos/1")?;

    if !response.status().is_success() {
        println!("Error: {}", response.text()?);
        return Ok(());
    }

    let json: Value = response.json()?;
    println!("{:#?}", json);

    Ok(())
}

In this code, we first make a GET request to the URL specified. If the response status is not successful, we print the response text and return without attempting to parse the JSON. If the response status is successful, we convert the response to JSON using the json() method provided by the reqwest::Response struct. Finally, we use println!() to display the JSON in pretty-printed format.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-30 06:26:22 +0000

Seen: 12 times

Last updated: Apr 30 '23