Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.