LeMoussel
LeMoussel

Reputation: 5767

How to use boost property tree to parse elements from array in json string using boost?

I have a json string that looks like this:

   [
      "some text", 
      648547, 
      94.0, 
      111.0267520223, 
      10
   ]

so I need to assign a variable to each value like:

std::string value1 = "some text";
int value2 = 648547;
float value3 = 94.0;
float value4 = 111.0267520223;
int value5 = 10;

to read JSON, with Boost, I was doing something like this

std::stringstream jsonResponse;
boost::property_tree::ptree pt;

jsonResponse << "[\"some text\", 648547, 94.0, 111.0267520223, 10]";
std::istringstream is(jsonResponse);
boost::property_tree::read_json(is, pt);

But I don't know how to read array values from a property tree.

Does anyone have an idea how to do it?

thanks in advance!

Here my solution to iterate over no naming array:

boost::property_tree::basic_ptree<std::string,std::string>::const_iterator iter = pt.begin(),iterEnd = pt.end();
for(;iter != iterEnd;++iter)
{
    //->first;  // Key.  Array elements have no names 
    //->second; // The object at each step

    std::cout << "=> " << iter->second.get_value<std::string>() << std::endl;
}

Upvotes: 2

Views: 2474

Answers (1)

stack user
stack user

Reputation: 863

You'll need to name the array so that it can be referenced:

{
    "blah": [
        "some text",
        648547,
        94.0,
        111.0267520223,
        10
    ]
}

This will validate on jsonlint.com, but it's still not simple to read using a property tree.

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/exception/diagnostic_information.hpp> 
#include <boost/foreach.hpp>

typedef boost::property_tree::iptree    ptree_t;
typedef ptree_t::value_type             ptree_value_t;
typedef boost::optional<ptree_t &>      optional_ptree_t;


void parseMyJson()
{
    optional_ptree_t ptBlah = pt.get_child_optional("blah");

    if (ptBlah)
    {
        BOOST_FOREACH (property_tree_t::value_type & field, pt.get_child("blah"))
        {

        }
    }
}

With this kind of code you can iterate the fields in blah, but since they're different types, its not straightforward to parse.

I would suggest that you consider naming the fields so they can be directly referenced.

e.g.

field.second.get<string>("fieldname", "");

Please remember to wrap this code in a trycatch block, since boost property trees throw exceptions at the first sign of a problem (e.g. parse failure, or field not found etc.)

You might like to consider a more user friendly json library (https://github.com/nlohmann/json).

Upvotes: 2

Related Questions