Skip to content

Cant modify existing numbers inside a json object #557

Closed

Description

@AMScaglione

Say for example I have something like

json j;
j["num"] = 0;

I can not do something like

j["num"] += 1;

as it gives me this error on runtime:

terminate called after throwing an instance of 'std::domain_error'
  what():  cannot use push_back() with number

I tried simplifying it to

j["num"] = j["num"] + 1;

but that gives me this error at compile time:
error: no match for 'operator+' (operand types are 'nlohmann::basic_json<>::value_type {aka nlohmann::basic_json<>}' and 'int')|

Activity

  1. gregmarr commented on Apr 17, 2017

    @gregmarr
    Contributor

    j["num"] is a json object, not an int. You need to get() the int out of it before you can add 1 to it and assign it back again.

  2. nlohmann commented on Apr 19, 2017

    @nlohmann
    Owner

    In addition to @gregmarr s remarks: += is an overload for json::push_back and can only be called on a JSON array. And indeed the + operator has no overload for json and int.

    To increment j["num"], you need to call

    j["num"] = j["num"].get<int>() + 1;

    or

    j["num"] = int(j["num"]) + 1;
    
  3. nlohmann commented on Apr 22, 2017

    @nlohmann
    Owner

    @AMScaglione Does this work for you?

  4. AMScaglione commented on Apr 23, 2017

    @AMScaglione
    Author
  5. nlohmann commented on Apr 23, 2017

    @nlohmann
    Owner

    No problem.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions