Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I turn a string of a json array into a json array? #1526

Closed
Gomox11 opened this issue Mar 19, 2019 · 2 comments
Closed

How can I turn a string of a json array into a json array? #1526

Gomox11 opened this issue Mar 19, 2019 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@Gomox11
Copy link

Gomox11 commented Mar 19, 2019

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!

@nlohmann
Copy link
Owner

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).

@Gomox11
Copy link
Author

Gomox11 commented Mar 19, 2019

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;

@Gomox11 Gomox11 closed this as completed Mar 19, 2019
@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Mar 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants