【问题标题】:For a Boost.Propertytree, is there any way to use JSON dot notation to reference an array element?对于 Boost.Propertytree,有没有办法使用 JSON 点表示法来引用数组元素?
【发布时间】: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


    【解决方案1】:

    难以置信——

    这个语法正是我正在寻找的:

    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])都有自己的 OWN 子节点,其中包含 BarIntValue 和 BarString。不是我所期望的,但它有效!

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

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 2019-08-23
      • 2021-07-31
      • 1970-01-01
      • 2011-02-26
      • 2022-07-06
      相关资源
      最近更新 更多