【问题标题】:How can I parse JSON arrays with C++ Boost?如何使用 C++ Boost 解析 JSON 数组?
【发布时间】:2013-06-12 01:22:13
【问题描述】:

我有一个包含一些 JSON 内容的文件,如下所示:

{
  "frame":
  {
    "id": "0",
    "points":
    [
      [ "0.883", "0.553", "0" ],
      [ "0.441", "0.889", "0" ],
    ]
  },
  "frame":
  ...
}

如何使用 C++ 和 Boost ptree 解析双精度数组的值?

【问题讨论】:

标签: c++ json boost ptree


【解决方案1】:

使用迭代器,Luke。

首先,你必须解析文件:

boost::property_tree::ptree doc;
boost::property_tree::read_json("input_file.json", doc);

...现在,因为您似乎在顶级字典中有多个“框架”键,您必须遍历它们:

BOOST_FOREACH (boost::property_tree::ptree::value_type& framePair, doc) {
    // Now framePair.first == "frame" and framePair.second is the subtree frame dictionary
} 

遍历行和列是一样的:

BOOST_FOREACH (boost::property_tree::ptree::value_type& rowPair, frame.get_child("points")) {
    // rowPair.first == ""
    BOOST_FOREACH (boost::property_tree::ptree::value_type& itemPair, rowPair.second) {
        cout << itemPair.second.get_value<std::string>() << " ";
    }
    cout << endl;
}

我没有测试代码,但这个想法会奏效:-)

【讨论】:

  • get_value 是一个函数,所以你需要()。尚未设置提升,但它看起来合法。
  • 如您所说,使用 framePair.second.get_child("points") 为我工作,我不得不将 cout 中的数据类型从 double 更改为 string。谢谢你的帮助!!
  • 谢谢,我解决了你提到的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多