【发布时间】:2019-06-21 17:39:03
【问题描述】:
如果能够指定到包含数组的 Boost.PropertyTree 的路径,那就太好了。
我可以从这个 JSON 构造一个 Boost.PropertyTree:
const char* theJSONTestText = R"FooArrayTest({
"FooArray": [
{"BarIntValue": 10, "BarString": "some string"},
{"BarIntValue": 99, "BarString": "another string"},
{"BarIntValue": 45, "BarString": "a third string"}
]
})FooArrayTest";
按预期构造和打印:
FooArray:
:
BarIntValue: 10
BarString: some string
:
BarIntValue: 99
BarString: another string
:
BarIntValue: 45
BarString: a third string
当然,数组的各个元素没有名称。
我知道如何遍历 FooArray 属性,但如果能够通过 JSON 点符号路径(例如“FooArray[2].BarString”)访问单个元素以访问第三个字段中的字段,将特别方便数组元素:
std::string theSecondBarString = theParsedTree.get<std::string>("FooArray[2].BarString");
当然,这会引发异常,因为我猜 Boost.PropertyTree 不知道如何处理带有数组说明符的路径?还是我语法错误?
我为什么要这样做?
我希望这个 PropertyTree 的客户端不仅能够从特定数组元素中获取数据,而且能够设置(即更改)特定数组元素的数据。如果没有直接的路径符号,那么客户端必须使用我发明的 API 函数首先提取然后访问所需的字段,然后反过来将其写回。对于在数组元素中包含数组元素的树节点,这可能是乏味且容易出错的。
【问题讨论】:
标签: c++ json boost boost-propertytree