2

I am attempting to read array data from a boost::property_tree using the method shown in this question. In that example, the array is first read as a string, converted to a string stream, then read into an array. While implementing that solution, I have noticed that my strings are coming up empty.

Example input (json):

"Object1"
{
  "param1" : 10.0,
  "initPos" :
  {
    "":1.0,  
    "":2.0, 
    "":5.0 
  },
  "initVel" : [ 0.0, 0.0, 0.0 ]
}

Both of these array notations are interpreted as arrays by the boost json parser. I am confident that the data is present int the property tree, because on invocation of the json writer, the array data is present in the output.

This is an example of what is failing:

std::string paramName = "Object1.initPos";
tempParamString = _runTree.get<std::string>(paramName,"Not Found");
std::cout << "Value: " << tempParamString << std::endl;

When paramName is "Object1.param1" I get "10.0" output as a string, When paramName is "Object1.initPos" I get an empty string, If paramName is something that does not exist in the tree, "Not Found" is returned.

Community
  • 1
  • 1
2NinerRomeo
  • 2,687
  • 4
  • 29
  • 35

1 Answers1

0

First, make sure the JSON provided is valid. It looks there are some problems with it. Next, you cannot get Object1.initPos as string. Its type is boost::property_tree::ptree. You can get it using get_child and process it.

#include <algorithm>
#include <string>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp> 

using namespace std;
using namespace boost::property_tree;

int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        std::string j("{ \"Object1\" : { \"param1\" : 10.0, \"initPos\" : { \"\":1.0, \"\":2.0, \"\":5.0 }, \"initVel\" : [ 0.0, 0.0, 0.0 ] } }");
        std::istringstream iss(j);

        ptree pt;
        json_parser::read_json(iss, pt);

        auto s = pt.get<std::string>("Object1.param1");
        cout << s << endl; // 10

        ptree& pos = pt.get_child("Object1.initPos");
        std::for_each(std::begin(pos), std::end(pos), [](ptree::value_type& kv) { 
            cout << "K: " << kv.first << endl;
            cout << "V: " << kv.second.get<std::string>("") << endl;
        });
    }
    catch(std::exception& ex)
    {
        std::cout << "ERR:" << ex.what() << endl;
    }

    return 0;
}

Output:

10.0
K:
V: 1.0
K:
V: 2.0
K:
V: 5.0
Grigorii Chudnov
  • 3,046
  • 1
  • 25
  • 23