Parsing nested json retrieved with reqwest

I'm trying to parse JSON data retrieved from a URL like the following example in to a struct format.

{
  "component-1": [
    {
      "application": "application_name",
      "host": "current_host",
      "id": "error_id",
      "level": "level_0",
      "timestamp": 1751549524436,
      "datehuman": "2025-07-03T13:32:04.436"
    },
    {
      "application": "application_name",
      "host": "current_host",
      "id": "error_id2",
      "level": "level_2",
      "timestamp": 1751549524436,
      "datehuman": "2025-07-03T13:32:04.436"
    }
  ]
   "component-2": [
    {
      "application": "application_name",
      "host": "current_host",
      "id": "error_id",
      "level": "level_1",
      "timestamp": 1751549524437,
      "datehuman": "2025-07-03T13:33:04.436"
    },
}

I thought the following would work

use serde_derive::{Serialize, Deserialize}; 

struct FaultLists {
    application: String,
    host: String,
    id: String,
    level: String,
    timestamp: u64,
}

#[allow(non_snake_case, dead_code)] 
#[derive(Deserialize, Debug)]
struct Component {
    component: Vec<FaultList>
}

#[tokio::main]
async fn main() -> Result<()> {

    let client = reqwest::Client::new();
    let res = client.get("https://supercoolurl.com/json").send().await?;

    let end: Component = res.json().await.unwrap();

  //println!("{:?}", end);
   Ok(())

But when trying to print I get the following error

called `Result::unwrap()` on an `Err` value: reqwest::Error { kind: Decode, source: Error("missing field `component`", line: 1, column: 555) }

Obviously I'm just starting out so any help is appreciated :slight_smile: Thanks1

The top-level structure is a JSON object, not an array. I'd probably do something like this in your case:

use serde_derive::{Serialize, Deserialize}; 
use std::collections::HashMap;

struct FaultLists {
    application: String,
    host: String,
    id: String,
    level: String,
    timestamp: u64,
}

#[allow(non_snake_case, dead_code)] 
#[derive(Deserialize, Debug)]
struct Component {
    #[serde(flatten)]
    component: HashMap<String, Vec<FaultList>>,
}

#[tokio::main]
async fn main() -> Result<()> {

    let client = reqwest::Client::new();
    let res = client.get("https://supercoolurl.com/json").send().await?;

    let end: Component = res.json().await.unwrap();

   //println!("{:?}", end);
   Ok(())
}

In a secondary step, you could flatten the vectors in the hash map into a single one. Alternatively, you could implement DeserializeSeed for Component by hand and implement the flattening in there.

2 Likes

I added the step of using #[serde(flatten)] and HashMap and now it does work on a first glance thank you so much for your swift response

In a secondary step, you could flatten the vectors in the hash map into a single one. Alternatively, you could implement DeserializeSeed for Component by hand and implement the flattening in there.

I'll be sure to look at it.