Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two JSONObject structures (ignoring their values)?

I'm looking for a JSON paring library that supports comparing two JSON objects' structures, ignoring values, child order, and - if possible - optionally ignoring additional elements in the response; specifically for unit testing JSON returning from a web service against an expected structure. (I'd like to pass into the assert method a sample response and compare its structure to the actual response - instead of having to write asserts for each node. Getting different values back isn't a problem, as long as the structure is fine.)

Do any of the major JSON libraries support this? (This question is basically the same as Compare two JSON objects in Java, but I want the assert to ignore the values in my JSON structure, which might look like the example found on Wikipedia...)

like image 807
Christian Avatar asked Mar 10 '14 18:03

Christian


People also ask

How do you compare two JSON objects?

Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.

How to compare two JsonObject in Java?

Compare JSON Objects with Custom Comparator The JsonNode. equals() method works fine for most of the cases in comparing two objects. However, Jackson provides one more variant of the equals() method, i.e., JsonNode. equals(comparator, JsonNode) for configuring the custom Java Comparator object.

How do you compare two JSON objects in Python?

Use json. dumps() and the equal-to operator to compare JSON objects regardless of order. Call json. dumps(json_object, sort_keys) with sort_keys set to True on each json_object to return the object with its key-value pairs sorted in ascending order by the keys.

How do I compare two JSON objects in Node JS?

Your first code step would be to convert the JSON string to an object, using JSON. parse . Then you can use Object. keys to get all keys from the first object, and you can loop over these keys to see the difference in values in the two objects.


1 Answers

You may want to have a look at Guava and its Equivalence.

If for instance you use Jackson, you would write an Equivalence<JsonNode>, which you would customize for your needs.

Here is an example of such an Equivalence, which considers two JSON values equal if all numbers, recursively, are mathematically equal.

Usage: yourEquivalence.equivalent(node1, node2).

Another solution would be to write a POJO which serializes to the JSON you want and attempt to deserialize your JSON to said POJO. If deserialization fails your structure is wrong.

like image 145
fge Avatar answered Nov 07 '22 08:11

fge