Saturday, July 10, 2010

Every day JSON work: comparing JSON documents for equality ("are these JSONS same?")

One JSON task that may seem trivial but is not is that of checking whether two given JSON documents are equal: that is, have same structure and values, and ordering of array values is same. It is not sufficient to use String equality comparison because while equality of Strings does mean contained JSON is equal, differing Strings does not mean they are not equal, since:

  • It is possible to quote characters differently using \uXXXX mechanism
  • Order of properties of JSON objects is undefined (at conceptual level); meaning that physical ordering may differ while conceptually JSON is still identical

So how should one compare equality? With Jackson, simplest way is to construct JSON tree (JsonNode) for documents to compare and just use JsonNode.equals()! Like so:

  ObjectMapper mapper = new ObjectMapper();
  JsonNode tree1 = mapper.readTree(input1);
  JsonNode tree2 = mapper.readTree(input2);
  boolean areEqual = tree1.equals(tree2);

I realized that this (fact that JsonNode.equals() works "as expected", doing deep value comparison) is not documented outside of Javadocs (it will be now, I will add something at FasterXML Jackson Wiki). But hopefully it was already known by experienced Jackson users. Either way, here's how JSON content comparison can be done easily and reliably.

blog comments powered by Disqus

Sponsored By


Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me at@yahoo.com
Check my profile to learn more.