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

cannot parse from string? #1349

Closed
addriumruss opened this issue Nov 12, 2018 · 4 comments
Closed

cannot parse from string? #1349

addriumruss opened this issue Nov 12, 2018 · 4 comments

Comments

@addriumruss
Copy link

addriumruss commented Nov 12, 2018

here is my code:

#include <stdio.h>
#include<stdlib.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main(int argc, char **argv){

// create object from string literal
// parse explicitly
std::string text = "{ \"happy\": true, \"pi\": 3.141 }";
auto j = json::parse(text);

std::string str = j.dump();

printf("j=%s \n", str);

printf("happy=%d, pi=%f \n", j["happy"], j["pi"]);

return 0;
}

this is build:
g++ -Wall -std=c++14 -I./json/include -L./json/lib test4.cpp -o t4

and result:
./t4
j=
happy=25431392, pi=0.000000

@nlohmann
Copy link
Owner

For printf's %s, you need to provide a char pointer:

printf("j=%s \n", str.c_str());

In general, the mixture between the class and C-style code may need additional casting.

Could you try:

printf("happy=%d, pi=%f \n", j["happy"].get<bool>(), j["pi"].get<double>());

Or just use std::cout << "happy=" << j["happy"] ...

@addriumruss
Copy link
Author

@nlohmann Thank you so much! I'm really appreciated!
I did it as you told and solved the problem.
j={"happy":true,"pi":3.141}
happy=1, pi=3.141000

and also got these two tip:
j={"happy":"true","pi":"3.141"}
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be number, but is string
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be boolean, but is string

it seems the value part must be the strict type match as ".get" told, when I use it to communicate to a java server which using gson or fastjson or from the web client, there would be quoted numbers. Is there any features to switch on for these situations?

@nlohmann
Copy link
Owner

The library does not perform implicit conversions such as from string to numbers.

@addriumruss
Copy link
Author

got it.
@nlohmann , Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants