gpt4 book ai didi

c++ - 对于 Boost.Propertytree,有什么方法可以使用 JSON 点符号来引用数组元素?

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:16 25 4
gpt4 key购买 nike

如果能够将路径指定到包含数组的 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 函数来首先提取然后访问所需的字段,然后反过来将其写回。对于在数组元素中包含数组元素的树节点,这可能是乏味且容易出错的。

最佳答案

不可思议——

这个语法构造了我正在寻找的东西:

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";

...创建一个像这样的 PropertyTree:

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

...并允许使用如下语法:

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

...并且——瞧:

Second bar string = another string

重要提示:必须注意,这种方法放弃了原始 JSON 定义文本中的数组符号“[”、“]”。相反,我只是用名称“[n]”创建 SomeArray 的子节点。每个子节点 ([1]、[2]、[3]) 都有自己的带有 BarIntValue 和 BarString 的子节点。出乎我的意料,但它确实有效!

现在我只需要弄清楚如何使用成员函数(与原始 JSON 相比)构造 PropertyTree,我很成功!

关于c++ - 对于 Boost.Propertytree,有什么方法可以使用 JSON 点符号来引用数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com