Boost::JSON, parsing string
So this is my JSON:
string js = R"({"table":"orderBookL2_25","action":"insert","data":[{"symbol":"XBTUSD","id":8796514950,"side":"Buy","size":10000,"price":34850.5},{"symbol":"XBTUSD","id":8796515700,"side":"Buy","size":281,"price":34843}]})";
I want to somehow convert it into object that could help me to conveniently access values. For example, something like that;
parsed_data["data"][0]["symbol"]
I have tried to use JSON::Boost but I don't know how to parse using this library. I have tried this code:
json::value parsed_data{js}; cout << parsed_data.at(0);
But the output from it is worthless:
"{\"table\":\"orderBookL2_25\",\"action\":\"insert\",\"data\":[{\"symbol\":\"XBTUSD\",\"id\":8796514950,\"side\":\"Buy\",\"size\":10000,\"price\":34850.5},{\"symbol\":\"XBTUSD\",\"id\":8796515700,\"side\":\"Buy\",\"size\":281,\"price\":34843}]}"
Solution 1:
Basically your code (which you showed in fuzzy way) assigned string to JSon value object, that is why some signs has been escaped.
Problem is that you do not read documentation.
Please read JSon quick look note section how to parse input:
Quick Look - 1.75.0
Parsing
JSON can be parsed into the value container in one step using a free function. In the following snippet, a parse error is indicated by a thrown exception:
value jv = parse( "[1, 2, 3]" );
Error codes are also possible:
error_code ec; value jv = parse( R"( "Hello, world!" )", ec );
Then fix code for example like this:
#include <iostream>
#include <vector>
#define BOOST_JSON_STACK_BUFFER_SIZE 1024
#include <boost/json/src.hpp>
#include <boost/json.hpp>
using namespace boost::json;
int main()
{
std::string js = R"({
"table":"orderBookL2_25",
"action":"insert",
"data":[
{
"symbol":"XBTUSD",
"id":8796514950,
"side":"Buy",
"size":10000,
"price":34850.5
},
{
"symbol":"XBTUSD",
"id":8796515700,
"side":"Buy",
"size":281,
"price":34843
}
]
})";
try {
auto parsed_data = parse(js);
std::cout << value_to<std::string>(parsed_data.at("data").at(0).at("symbol")) << '\n';
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return 0;
}
Live demo