18

I am trying to make a minimal example of reading a json string that is passed as a command line arg with boost. I am very new to C++ and to boost.

My code is:

int main (int argc, char ** argv)
{
  boost::property_tree::ptree pt;
  boost::property_tree::read_json(argv[1], pt);
  cout << pt.get<std::string>("foo");
}

I am calling it like

./myprog "{ \"foo\" : \"bar\" }"

But I get a 'cannot open file error'. How do I get boost to read a std::string or a char* rather than a file?

Thanks

asutherland
  • 2,849
  • 4
  • 32
  • 50
  • See this: http://stackoverflow.com/questions/12542399/boost-property-treejson-parserread-json-iostreamsfiltering-streambuf. read_json expects a stream, and you're giving it a string. – bstamour Feb 03 '14 at 21:07

1 Answers1

35

What you can do is read the characters into a string stream, and then pass that to read_json.

#include <sstream>
#include <iostream>

#include <boost/property_tree/json_parser.hpp>

int main (int argc, char ** argv)
{
  std::stringstream ss;
  ss << argv[1];

  boost::property_tree::ptree pt;
  boost::property_tree::read_json(ss, pt);
  std::cout << pt.get<std::string>("foo") << std::endl;
}

outputs

bar
bstamour
  • 7,746
  • 1
  • 26
  • 39