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

Cant modify existing numbers inside a json object #557

Closed
AMScaglione opened this issue Apr 16, 2017 · 5 comments
Closed

Cant modify existing numbers inside a json object #557

AMScaglione opened this issue Apr 16, 2017 · 5 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@AMScaglione
Copy link

AMScaglione commented Apr 16, 2017

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

@gregmarr
Copy link
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.

@nlohmann
Copy link
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;

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Apr 19, 2017
@nlohmann
Copy link
Owner

@AMScaglione Does this work for you?

@AMScaglione
Copy link
Author

AMScaglione commented Apr 23, 2017 via email

@nlohmann
Copy link
Owner

No problem.

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

3 participants