使用boost :: property_tree :: string_path访问值 [英] Accessing values using a boost::property_tree::string_path

查看:87
本文介绍了使用boost :: property_tree :: string_path访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩 boost :: property_tree :: ptree ,即使用以下 json文件

I am playing with boost::property_tree::ptree, using namely the following json file:

{
    "menu":
    {
        "foo": "true",
        "bar": "true",
        "value": "102.3E+06",
        "popup":
        [
            {
                "value": "New",
                "onclick": "CreateNewDoc()"
            },
            {
                "value": "Open",
                "onclick": "OpenDoc()"
            }
        ]
    }
}

到目前为止,我一直在尝试访问嵌套的值而没有运气,这是我所做的:

I have been trying to access nested "value" with no luck so far, here is what I did:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>

int main(int argc, char *argv[])
{
  const char *filename = argv[1];
  using boost::property_tree::ptree;
  ptree pt;

  read_json(filename, pt);

  std::string v0 = pt.get<std::string>("menu.value"); // ok
  //std::string v1 = pt.get<std::string>("menu.popup.value"); // not ok
  //std::string v2 = pt.get<std::string>("menu.popup.1.value"); // not ok
  //std::string v3 = pt.get<std::string>("menu.popup.''.value"); // not ok

  // ugly solution:
  BOOST_FOREACH(ptree::value_type &v,
    pt.get_child("menu.popup"))
    {
    const ptree &pt2 = v.second;
    std::string s = pt2.get<std::string>("value");
    }
  return 0;
}

我所有的尝试不好 都失败了,所以远。就像人们可以想象的那样,string_path似乎不允许访问整个ptree(请考虑XML世界中的XPath)。还是我错过了什么?

All my attempts "not ok" failed so far. It seems that string_path does not allow accessing the whole ptree, as one could imagine (think XPath in XML world). Or am I missing something ?

推荐答案

属性树(自1.54开始)不支持数组。您可以看到JSON ptree序列化程序如何将JSON数组对象转换为合适的(未命名; key =)节点此处

Property tree (as of 1.54) doesn't support arrays. You can see how the JSON ptree serializer translates JSON array objects into suitable (unnamed; key="") nodes here.

Ptree的字符串路径通过解析值密钥路径(密钥名称由点分隔)。由于数组对象最终以未命名的节点结尾,因此无法访问单个节点,而无需迭代根节点的子节点(在这种情况下为弹出)。您可以阅读如何使用这里的各种get()重载

Ptree's string paths resolve values by a key path (where key names are separated by dots). Since the array objects end up as unnamed nodes, there's no way to access individual nodes without iterating the children of the root node (in this case "popup"). You can read up on how to use the various get() overloads here

Ptree的五分钟示例使用了具有元素(模块 )的子级数组(每个名为模块)。就像您的情况一样,正确访问每个对象的唯一方法是迭代get_child()的结果

Ptree's five minute example uses an XML source that has an element ("modules") with an array of children (each named "module"). Just like in your case, the only way to properly access each one is to iterate get_child()'s results

这篇关于使用boost :: property_tree :: string_path访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆