Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 212
user934801 Avatar asked Jun 15 '13 14:06

user934801


People also ask

Can you JSON parse an array?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

Is boost JSON header only?

FWIW Boost. Json in particular doesn't have any source files, it's just header-only templates. You don't actually need to build or link boost to use it; you just need the header files to be in the include path. It does seem to have a very similar interface to this and has the performance of RapidJSON.

Is JSON fast to parse?

It's definitely much, much slower than MySQL (for a server) or SQLite (for a client) which are preferrable. Also, JSON speed depends almost solely on the implementation. For instance, you could eval() it, but not only that is very risky, it's also slower than a real parser.


1 Answers

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

like image 153
cube Avatar answered Sep 28 '22 02:09

cube