It would be nice to include as part of the library a way to compare JSON object in a way that the order is not important.
I though maybe defining operator&& to do it.
auto example1 = R("{
"name": "Rafa",
"age": 38,
"hobbies": [ "windsurfing", "cards", { "name": "sailing", "difficulty": 4 } ]
}")_json;
if (R("{ "name": "Rafa", "hobbies": [ { "name": "sailing" }, "cards" ] }")_json && example1)
std::cout << "example1 contains name: Rafa with hobbies sailing object and cards string\n";
//Or maybe nicer syntax:
if (example1.contains(R("{ "name": "Rafa", "hobbies": [ { "name": "sailing" }, "cards" ] }")_json))
std::cout << "Yes, example1 contains the json object passed by parameter\n";
Obviously, this example is very simple but it could work with more complex objects.
This could be a very simplistic implementation:
operator&&(const json & lhs, const json & rhs)
{
bool equal = false;
if (lhs.type() == rhs.type())
{
if (lhs.is_array())
{
equal = true;
for (const auto &lhs_item : lhs.items())
{
equal = false;
for (const auto rhs_item : rhs.items())
{
if (lhs_item.value() && rhs_item.value())
{
equal = true;
break;
}
}
if (!equal) break;
}
}
else if (lhs.is_object())
{
equal = true;
for (const auto &item : lhs.items())
{
auto res = rhs.find(item.key());
if ((res == rhs.end()) || (res->type() != item.value().type()) || !(item.value() && *res))
{
equal = false;
break;
}
}
}
else
{
equal = (lhs == rhs);
}
}
return equal;
}
Sorry, if I'm not using the library the best way. I have just started to use it today.
Instead of using the operators, it maybe nicer to extend the json object to have a .contains method (or several depending on parameters).
Also, it would be nice to consider providing options like "arrays might be in the same order" or take some considerations on duplicated keys, ...
I'd like to use this function for testing. For example, I want to know if the JSON returned by a function contains at least the keys I expect it to have even if it has more or in a different order and with the values and types I expect.
It would be nice to include as part of the library a way to compare JSON object in a way that the order is not important.
I though maybe defining operator&& to do it.
Obviously, this example is very simple but it could work with more complex objects.
This could be a very simplistic implementation:
Sorry, if I'm not using the library the best way. I have just started to use it today.
Instead of using the operators, it maybe nicer to extend the json object to have a .contains method (or several depending on parameters).
Also, it would be nice to consider providing options like "arrays might be in the same order" or take some considerations on duplicated keys, ...
I'd like to use this function for testing. For example, I want to know if the JSON returned by a function contains at least the keys I expect it to have even if it has more or in a different order and with the values and types I expect.