Skip to content

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

Closed

Description

@RElesgoe

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.

Activity

  1. nlohmann commented on Dec 18, 2015

    @nlohmann
    Owner

    Thanks for reporting! I'll check!

  2. nlohmann commented on Dec 20, 2015

    @nlohmann
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions