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

Error when serializing empty json: type must be string, but is object #740

Closed
sogartar opened this issue Sep 13, 2017 · 5 comments
Closed

Comments

@sogartar
Copy link

sogartar commented Sep 13, 2017

auto j = json::parse("{}");
std::string jstr1 = j.dump(); // OK
std::string jstr2 = j; // Exception

The last line raises:
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be string, but is object

On the other hand dump() works fine.

This appears on commit e2e0ecd867413b0489a339d32509ef649ff1af5a
Also on v2.1.1.

@nlohmann
Copy link
Owner

{} is an empty JSON object, and the library does not implement an implicit conversion from objects to string (which would be required to case from type nlohmann::json to std::string. Using j.dump() works, because it creates a string serialization.

What do you expect should be the value of jstr2?

@sogartar
Copy link
Author

OK, so it is a design goal to forbid it. I am not sure why but you probably have a good reason.
I was expecting the same value as was passed into parse.

@nlohmann
Copy link
Owner

The problem is that JSON itself allows string types. And when I then store string foo, the value is foo, but the serialization via dump() would be "foo"...

@gregmarr
Copy link
Contributor

What you were trying to do is get the value of j as if it held a string, but j does not hold a string, it holds an object, so it throws an exception to tell you that you tried to do something impossible.

If you want the "same" value that you passed into parse(), then you call dump(). Note that it's not guaranteed to be exactly the same as the JSON standard doesn't require any particular order of keys within an object, and floating point values may be changed if the values in the original string are not able to be represented exactly using double precision floating point.

@nlohmann
Copy link
Owner

Can I close this issue?

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

No branches or pull requests

3 participants