Boost ptree node for all children in a json array

2.1k Views Asked by At

I have been searching for an answer to this but cant find anything so sorry if this has been asked before. I have the following json file

{"GuiComponents": [
{
    "GuiComponent":
    {
        "screen": "WindowMain",
        "type": "class Robot",
        "filename": "robot.mesh",
        "blueprint": "Betplacement/Robot.json",
        "layer": "0",
        "position": 
        {
            "x": "0",
            "y": "0"
        }
    }
},
{
    "GuiComponent": 
    {
        "screen": "WindowTop",
        "type": "class Robot",
        "filename": "robot.mesh",
        "blueprint": "Betplacement/Robot.json",
        "layer": "0",
        "position": 
            {
            "x": "0",
            "y": "0"
            }
        }
    }
]
}   

Now I want to iterate over all the children in GuiComponents called GuiComponent and assign each child to a ptree node. This way I can simply pass a ptree node to anyone that wants to get the data for a specific GuiComponent without seeing all the other children. I cannot find a way to do this with get_child as it just throws a "No such node GuiComponent" exception.

Any help would be greatly appreciated.

Thanks

1

There are 1 best solutions below

2
On

Your GuiComponent elements are stored in unnamed elements of an array; when reading JSON data, Boost.PropertyTree will "translate" array elements into children of empty nodes.

Here is what you can try: search for empty nodes, and then search for elements GuiComponent within each node, using the equal_range() method:

auto array_iter = m_tree.equal_range("");
for (auto i: array_iter) {
  auto gui_iter = i->second.equal_range("GuiComponent");
  for (auto gui_component: gui_iter) {
    // ...
  }
}

An iterator on a ptree points to a pair where the first element is the name of the node and the second element is a ptree.