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

标签 c++ json boost boost-propertytree

如果能够将路径指定到包含数组的 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/

相关文章:

c++ - 使用多个字符串定界符拆分字符串

python - 如何使用 Boost.Python 使用带有 std::map 或 std::vector 参数的构造函数来包装 C++ 类?

c++ - 如何根据目标文件中缺少的符号来实例化模板?

c++ - Mongodb C++ 编译问题

c++ - "Explicit specialization of std::iterator_traits<char *> after instantiation"(CLang)

java - 解耦 JSON 服务中 unicode 转义导致的安全漏洞?

C++ 宏和 lambda 捕获

jquery - 如何使用json获取youtube中的视频图像URL

javascript - 如何将 Node.js 中的 JSON 中的十六进制字符串解析为十六进制数字

c++ - 重载模板函数的 std 绑定(bind)