Skip to content

ordered_json vs json types comparison #3443

Closed
@akontsevich

Description

@akontsevich

nlohman compares jsons as strings so comparing 2 equal nlohmann::ordered_json objects could produce wrong results:

using json = nlohmann::ordered_json; // ordered to preserve the insertion order for print
using ujson = nlohmann::json; // unordered json for testing comparison

    json j1 = { {"version", 1}, {"type", "mytype"} };
    json j2 = { {"type", "mytype"}, {"version", 1} };
    ujson j3 = ujson(j1);
    ujson j4 = ujson(j2);

    // nlohman compares jsons as strings, so...
    BOOST_CHECK_NE(j1, j2);     // these are not equal
    BOOST_CHECK_EQUAL(j3, j4);  // these are equal

So I would change operator== to this:

inline bool operator==(const nlohmann::ordered_json& lhs, const nlohmann::ordered_json& rhs) 
{
    return nlohmann::json(lhs) == nlohmann::json(rhs);
}

and add operator to compare json and nlohmann::ordered_json:

inline bool operator==(const nlohmann::json& lhs, const nlohmann::ordered_json& rhs) 
{
    return lhs == nlohmann::json(rhs);
}

and vice versa:

inline bool operator==(const nlohmann::ordered_json& lhs, const nlohmann::json& rhs) 
{
    return nlohmann::json(lhs) == rhs;
}

What do you think?

Compiler and operating system

gcc 9.4.0, Ubuntu 20.04.4 LTS

Library version

3.10.5

Validation

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions