Skip to content

Instantly share code, notes, and snippets.

@faizaanshamsi
Created April 25, 2016 18:37
Show Gist options
  • Save faizaanshamsi/70ae0964e7b658a7b350ebd77bbb0d49 to your computer and use it in GitHub Desktop.
Save faizaanshamsi/70ae0964e7b658a7b350ebd77bbb0d49 to your computer and use it in GitHub Desktop.
Compare Unordered JSON
module Helpers
module CompareJSON
def self.returning(value)
yield(value)
value
end
def self.order_and_sort_json(object, deep = true)
if object.is_a?(Hash)
# recursively sort the hash
res = returning(Hash.new) do |map|
object.each do |k, v|
map[k] = deep ? order_and_sort_json(v, deep) : v
end
end
# res returns and array, sort by first element (key)
# and transform back to hash if necessary
res.class[res.sort { |a, b| a[0].to_s <=> b[0].to_s }]
elsif deep && object.is_a?(Array)
# sort the array
sorted = object.sort_by { |h| h.is_a?(Hash) ? h["id"] : h }
array = Array.new
# recursively sort each array element and return a new array
sorted.each_with_index do |v, i|
array[i] = order_and_sort_json(v, deep)
end
array
else
object
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment