15

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user934801
  • 1,119
  • 1
  • 12
  • 30
  • http://www.boost.org/doc/libs/1_41_0/doc/html/property_tree/reference.html#header.boost.property_tree.json_parser_hpp – riv Jun 15 '13 at 14:34
  • PTree will accept it, but strictly speaking repeated property names are not valid JSON. – Sebastian Redl Jun 15 '13 at 23:36

1 Answers1

24

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 :-)

cube
  • 3,867
  • 7
  • 32
  • 52
  • `get_value` is a function, so you need `()`. Haven't set up boost but it looks legit otherwise. – riv Jun 15 '13 at 14:56
  • worked for me with framePair.second.get_child("points") as you said and i had to change the data type in the cout from double to string. thank you for helping!! – user934801 Jun 15 '13 at 16:29
  • Thanks, I fixed the problems you mentioned. – cube Jun 15 '13 at 23:12