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

Converting json::value to int #1605

Closed
JiazhengSun opened this issue May 22, 2019 · 3 comments
Closed

Converting json::value to int #1605

JiazhengSun opened this issue May 22, 2019 · 3 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@JiazhengSun
Copy link

So my json looks like this:
{ "22" : { "multi" : 2, func : [{type: "A", "number" : [1,2,3]}] } }

I want to get the value of "multi", which is 2. The code I have now looks like this:
for (auto& el : j.items()) { auto mul = el.value()["multi"]; }
It says that what I am getting is json::value type. I am wondering how to access it as an integer, as that's what I put in the json? Thanks.

@JiazhengSun JiazhengSun changed the title Convering json::value to int Converting json::value to int May 22, 2019
@JiazhengSun
Copy link
Author

OK I think I solved it (maybe)? I make the value of "22" as another json (tmp), and access that 2 with tmp["multi"]. I am not sure if this is the best solution. If there is a better one please enlighten me. If not you may feel free to close the issue. Awesome lib! :)

@nickaein
Copy link
Contributor

nickaein commented May 23, 2019

With auto x = tmp["multi"] you still get a json::value type for x, right? A workaround is to pin down the type, e.g. int x = tmp["multi"];. This triggers an implicit type conversion which is NOT recommended.

Instead, you should use APIs like basic_json::get().

Here is a live example for retrieving multi: https://wandbox.org/permlink/C5J5tsyXmFratpJx

Also, double quotations are required around func and type fields in JSON, otherwise it is not valid.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label May 24, 2019
@nlohmann
Copy link
Owner

@JiazhengSun Do you need further assistance?

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