Json: How can I turn a string of a json array into a json array?

Created on 19 Mar 2019  路  2Comments  路  Source: nlohmann/json

Hello!

I receive messages like these as a string:

[10, "1234", "Test"]

Now I want to turn this into a json object holding that array. It works when I pass the arguments by hand like this:

json j;
j = {10, "1234", "Test"};
std::cout << j[0] << j[1] << j[2]

But when I pass a string, everything except j[0] is null because the json object obviously treats the whole string as one object.

std::string json_string = "10, \"1234\", \"Test\"";
json j;
j = {json_string};
std::cout << j[0] << j[1] << j[2]

How can I solve this? Thanks in advance!

question proposed fix

All 2 comments

The message

[10, "1234", "Test"]

looks like valid JSON, so you can parse it:

json j = json::parse(s);

assuming s is a string with your message (or an std::ifstream).

Works like a charm! Thanks for your quick answer and the great library :)

nlohmann::json j;
std::string message = "[10, \"1234\", \"Test\"]";
j = nlohmann::json::parse(message);
std::cout << j[0] << j[1] << j[2] << std::endl;
Was this page helpful?
0 / 5 - 0 ratings