You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi. I receive a JSON from 2 different places that contain a number. one of them returns JSON with a number and the other returns the same JSON with a number with quotes. like this:
{"state": 0}
or:
{"state": "0"}
the problem is how can I read them with no problem?
my problem is that state can be number and also string that contains number. I want to assign this number to int variable but it is not possible to read it using normal assignment.
json jp = R"({"state": "10"})"_json;
int state = jp["state"]; // return 0 instead of value 10
json jp = R"({"state": 10})"_json;
int state = jp["state"]; // return 10 becuase it is number not string
Activity
nlohmann commentedon Mar 14, 2020
What is your exact issue? Deserialization (also know as parsing) is described here: https://github.com/nlohmann/json#serialization--deserialization
Behrouz-m commentedon Mar 14, 2020
my problem is that
statecan benumberand alsostringthat contains number. I want to assign this number to int variable but it is not possible to read it using normal assignment.nlohmann commentedon Mar 14, 2020
You can call
jp["state"].is_number()orjp["state"].is_string()to check the type.Behrouz-m commentedon Mar 14, 2020
I know that. I am looking for an easier way instead of checking types for every number type in json. what about
jp.get<int>("state")?nlohmann commentedon Mar 14, 2020
The library does not provide such conversions.