How can I parse JSON arrays with C++ Boost?

亡梦爱人 提交于 2019-12-20 09:38:03

问题


I have a file containing some JSON content that looks like:

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

How do I parse the values of the double array using C++ and Boost ptree?


回答1:


Use the iterators, Luke.

First , you have to parse the file:

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

... now, because it seems you have multiple "frame" keys in the top level dictionary you must iterate over them:

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

Iterating over the rows and columns is the same:

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

I didn't test the code, but the idea will work :-)



来源:https://stackoverflow.com/questions/17124652/how-can-i-parse-json-arrays-with-c-boost

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!