1

It would be great to be able to specify a path into a Boost.PropertyTree containing an array.

I can construct a Boost.PropertyTree from this JSON:

const char* theJSONTestText = R"FooArrayTest({
    "FooArray": [
                 {"BarIntValue": 10, "BarString": "some string"},
                 {"BarIntValue": 99, "BarString": "another string"},
                 {"BarIntValue": 45, "BarString": "a third string"}
    ]
})FooArrayTest";

Which is constructed, and prints as expected:

FooArray: 
: 
BarIntValue: 10
BarString: some string
: 
BarIntValue: 99
BarString: another string
: 
BarIntValue: 45
BarString: a third string

Of course, the individual elements of the array don't have names.

I know HOW to iterate through the FooArray property, but it would be especially convenient to be able to access individual elements via a JSON dot notation path, like "FooArray[2].BarString", to access a field in the third array element:

std::string theSecondBarString = theParsedTree.get<std::string>("FooArray[2].BarString");

Of course, this throws an exception, because I'm guessing Boost.PropertyTree doesn't know how to handle a path with an array specifier? Or do I have the syntax wrong?

WHY DO I WANT TO DO IT THIS WAY?

I want the client of this PropertyTree to not only be able to GET data from the a specific array element, but also to SET (i.e. change) the data of a specific array element. If there's no straightforward path notation, then the client has to use my invented API functions to first extract then access the desired field, and the reverse to write it back out. That can be tedious and error-prone for tree nodes that contain array elements within array elements.

SMGreenfield
  • 1,680
  • 19
  • 35

1 Answers1

0

Incredibly --

This syntax constructs exactly what I'm looking for:

const char* theJSONTestText = R"FooArrayTest({
    "SomeArray": {
        "[1]":  {"BarIntValue": 10, "BarString": "some string"},
        "[2]":  {"BarIntValue": 99, "BarString": "another string"},
        "[3]": {"BarIntValue": 45, "BarString": "a third string"}
    }
})FooArrayTest";

...which creates a PropertyTree like this:

DUMP OF parsed JSON:
SomeArray: 
[1]: 
BarIntValue: 10
BarString: some string
[2]: 
BarIntValue: 99
BarString: another string
[3]: 
BarIntValue: 45
BarString: a third string

...and allows a syntax such as:

std::string theSecondBarString = theParsedTree.get<std::string>("SomeArray.[2].BarString");

...and -- VOILA:

Second bar string = another string

IMPORTANT: it must be noted that this approach abandons the array notation "[", "]" in the original JSON definition text. Instead, I am simply creating CHILD NODES of SomeArray with the names "[n]". Each child node ([1], [2], [3]) have their OWN child nodes with BarIntValue and BarString. Not what I expected, but it WORKS!

Now I just need to figure out how to construct that PropertyTree using the member functions (vs the raw JSON) and I'm gold!

SMGreenfield
  • 1,680
  • 19
  • 35