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

basic_json::iterator::value() output includes quotes while basic_json::iterator::key() doesn't #158

Closed
RElesgoe opened this issue Dec 18, 2015 · 2 comments

Comments

@RElesgoe
Copy link

I've noticed that when iterating through a json object, calling value() wraps the string with quotes while key() doesn't. This should be changed so that either they both be wrapped with quotes or not wrapped at all.

@nlohmann
Copy link
Owner

Thanks for reporting! I'll check!

@nlohmann
Copy link
Owner

This is not a bug.

key() returns a std::string and value() returns a basic_json object. So the former gives you they key as it was stored, whereas the latter gives you a JSON serialization of the string. This includes escaping characters, see RFC 7159.

So if you want an escaped version of the key, you need to create a JSON value out of it first.

Example:

#include <json.hpp>

using nlohmann::json;

int main()
{
    json s = "\"quoted\"";
    json j = {{s, s}};

    std::cout << "output of j (json): " << j << "\n";
    std::cout << "output of the first key (std::string): " << j.begin().key() << "\n";
    std::cout << "output of the first key (json): " << json(j.begin().key()) << "\n";
    std::cout << "output of the first value (json): " << j.begin().value() << "\n";
    std::cout << "output of the first value (std::string): " << j.begin()->get<std::string>() << "\n";
}

Output:

output of j (json): {"\"quoted\"":"\"quoted\""}
output of the first key (std::string): "quoted"
output of the first key (json): "\"quoted\""
output of the first value (json): "\"quoted\""
output of the first value (std::string): "quoted"

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