Skip to content

Instantly share code, notes, and snippets.

@ftuyama
Created September 28, 2021 15:45
Show Gist options
  • Save ftuyama/7c53067925f9cd2fb61a8b77998e225c to your computer and use it in GitHub Desktop.
Save ftuyama/7c53067925f9cd2fb61a8b77998e225c to your computer and use it in GitHub Desktop.
Recursively compare json objects
require 'json'
def flatten_hash(param, prefix=nil)
param.each_pair.reduce({}) do |a, (k, v)|
if v.is_a?(Array)
v = v.map.with_index { |x, i| [i, x] }.to_h
end
if v.is_a?(Hash)
a.merge(flatten_hash(v, "#{prefix}#{k}."))
else
a.merge("#{prefix}#{k}".to_sym => v)
end
end
end
def print_csv(diff)
diff.map do |x|
x.join(",")
end.join("\n")
end
vortex = JSON.parse(File.read('vortex.json'))
search = JSON.parse(File.read('search.json'))
vortex_flatten = flatten_hash(vortex)
search_flatten = flatten_hash(search).invert
diff = vortex_flatten.map do |key, value|
if !search_flatten.key?(value)
[key, value]
end
end.compact
File.write('diff.csv', print_csv(diff))
File.write('diff_uniq.csv', print_csv(diff.uniq(&:last)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment