Question

I've been trying the past 2 days to find out how do I do the following thing in C++:

I have a json string:

[
     {
       "pid" : 0,
       "nick":"Foo",
       "score":12,
       "ping":50
     },
     {
       "pid":1,
       "nick":"Bar",
       "score":23,
       "ping":24
     }
]

I want to iterate over all these childs and put, for example, PlayerID's values in a std::vector so that I can return all of them.

Where I'm stuck is here:

// some code
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);

std::vector<int> players;
int pid;
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("pid")) // I also tried with pt or pt.get_child("")
{
    pid = v.second.data();
    players.push_back(pid);
}
return players;

I looked at the documentation but couldn't find anything good. Also, I've tried almost everything there and if it compiles without errors it'd give me what() expected object or something like that. I'm really stuck, any help is appreciated! Thanks in advance.

Was it helpful?

Solution

PropertyTree's JSON support is not typed - data() always returns a string.

The PTree that you get from parsing your JSON should consist of a root node that has one unnamed child for every array element. Each of these children has four named children for the values. The code to iterate it should be:

namespace bpt = boost::property_tree;
bpt::ptree pt;
bpt::read_json(ss, pt);

std::vector<int> players;
int pid;

BOOST_FOREACH(bpt::value_type& v, pt) { // iterate over immediate children of the root
  pid = v.second.get<int>("pid"); // use the converting path getter
  players.push_back(pid);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top