jsonclojureclojure-java-interop

Clojure json comparing


In some of my testing I am comparing json result between some http calls, today I am just comparing strings, which is too naive and not reliable for example if order changes. Can you please recommend how to compare two json that may come in a different order of the elements like:

{
  "k1":"v1",
  "k2":"v2"
}

and

{
  "k2":"v2",
  "k1":"v1"
}

Thanks Oded


Solution

  • Parse the JSON bodies to Clojure data structures with for example cheshire and compare those:

    (ns my.ns
      (:require 
       [cheshire.core :as json]))
    
    (def body1
      "{\"a\": 1, \"b\": 2}")
    
    (def body2
      "{\"b\": 2, \"a\": 1}")
    
    (= body1 body2)
    ;; => false
    
    (let [keywordize-keys? true]
      (= (json/decode body1 keywordize-keys?)
         (json/decode body2 keywordize-keys?)))
    ;; => true