Skip to content

reading int number and string number #1986

Closed

Description

@Behrouz-m

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?

Activity

  1. nlohmann commented on Mar 14, 2020

    @nlohmann
    Owner

    What is your exact issue? Deserialization (also know as parsing) is described here: https://github.com/nlohmann/json#serialization--deserialization

  2. Behrouz-m commented on Mar 14, 2020

    @Behrouz-m
    Author

    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
  3. nlohmann commented on Mar 14, 2020

    @nlohmann
    Owner

    You can call jp["state"].is_number() or jp["state"].is_string() to check the type.

  4. Behrouz-m commented on Mar 14, 2020

    @Behrouz-m
    Author

    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") ?

  5. nlohmann commented on Mar 14, 2020

    @nlohmann
    Owner

    The library does not provide such conversions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions