Parsing std :: string with Boost ptree
I have this code
std::string ss = "{ \"item1\" : 123, \"item3\" : 456, \"item3\" : 789 }";
// Read json.
ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string item1= pt2.get<std::string>("item1");
std::string item2= pt2.get<std::string>("item2");
std::string item3= pt2.get<std::string>("item3");
I need to parse a JSON string into std::string
as shown above, I tried to set a catch statement here, but the actual error is just<unspecified file>(1):
So my guess is that read_json is just reading a file and not a std :: string, how can this std::string
be parsed?
source to share
Your sample is read from the stream (ie "as a file" if you do). The stream is filled with your string. So you are parsing your string. You cannot parse the string directly.
However, you can use Boost Iostreams to read from the original string directly without a copy:
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
namespace pt = boost::property_tree;
std::string ss = "{ \"item1\" : 123, \"item2\" : 456, \"item3\" : 789 }";
int main()
{
// Read json.
pt::ptree pt2;
boost::iostreams::array_source as(&ss[0], ss.size());
boost::iostreams::stream<boost::iostreams::array_source> is(as);
pt::read_json(is, pt2);
std::cout << "item1 = \"" << pt2.get<std::string>("item1") << "\"\n";
std::cout << "item2 = \"" << pt2.get<std::string>("item2") << "\"\n";
std::cout << "item3 = \"" << pt2.get<std::string>("item3") << "\"\n";
}
This will just copy less. This will not generate various error messages.
Consider including line breaks on a line so that the parser reports line numbers.
source to share