Checking if a value in a boost property tree is a tree or a terminal value
Asked Answered
C

1

10

I have been looking for APIs in boost::property_tree (that is used for reading a json) that I can use to determine if a value of a field is a tree or a terminal value. For example, I have a json where the value of foo can either be a tree as illustrated in the first block or a string as illustrated in the second block.

{
    "foo": {
        " n1": "v1",
        "n2": "v2"
    }
}

{
    "foo": "bar"
}

I know we can check first with get_child_optional. If the returned value is null, then we can check get_optional. But are there any better ways/apis to do this?

Calypso answered 4/3, 2013 at 5:24 Comment(0)
F
14

Try this:

property_tree pt;
...

if(pt.empty())
    cout << "Node doesn't have children" << endl;

if(pt.data.empty())
    cout << "Node doesn't have data" << endl;

if(pt.empty() && !pt.data.empty())
    cout << "Node is terminal value" << endl;

if(!pt.empty() && pt.data.empty())
    cout << "Node is a tree" << endl;
Fatherly answered 4/2, 2014 at 15:54 Comment(1)
I'm using boost 1.62 and I must write pt.data().empty() instead of pt.data.empty().Microcopy

© 2022 - 2024 — McMap. All rights reserved.