Skip to content

Trying to retrieve data from nested objects #1038

@EtienneBerube

Description

@EtienneBerube

Hi, I'm trying to map data from a Json file to individual objects in order to sort them and perform other operations on them. However, the data structure required is quite complex and makes it hard to navigate.
Here is a snippet of the Json file:

{
  "items":
  {
    "item":
    [
      {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
        {
          "batter":
          [
            { "id": "1001", "type": "Regular" },
            { "id": "1002", "type": "Chocolate" },
            { "id": "1003", "type": "Blueberry" },
            { "id": "1004", "type": "Devil's Food" }
          ]
        },
        "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5005", "type": "Sugar" },
          { "id": "5007", "type": "Powdered Sugar" },
          { "id": "5006", "type": "Chocolate with Sprinkles" },
          { "id": "5003", "type": "Chocolate" },
          { "id": "5004", "type": "Maple" }
        ]
      },
      [...] Other items could be there
    ]
  }
}

I cannot change the way it is organised. However, I cannot figure out how to properly get every element and extract it.

My current code:

ifstream input("sample.json");

    json json1;

    input >> json1;

    json json2 = json1["items"]["item"];

    for ( auto& item : json2.get<json::object_t>() ){
        Item *tempItem = new Item();

        tempItem->setId(item.at("id"));
        tempItem->setName(item.at("name"));
        tempItem->setType(item.at("type"));
        tempItem->setId(item.at("ppu"));
        //Trying to go in the array batters
        object_t temp_obj = item.at("batters");

        items.push_back(new Item());
    }

Note: Even then I get an error because json2.get<json::object_t>() returns a pair<>.

Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions