Skip to content

Instantly share code, notes, and snippets.

@granolocks
Last active December 23, 2015 19:49
Show Gist options
  • Select an option

  • Save granolocks/6685174 to your computer and use it in GitHub Desktop.

Select an option

Save granolocks/6685174 to your computer and use it in GitHub Desktop.
JSON Patching and Diffing..
require 'jsondiff' # https://github.com/francois2metz/jsondiff
require 'json/patch' # https://github.com/guillec/json-patch
def test_1
hash_1 = {a: {b:"sexy key"}, c: [1,2,3], x: "gonna remove this one"}
json_1 = JSON.generate(hash_1)
hash_2 = {a: {b:"new key", b2: "sexier key"}, c: [2,3,4], d: "a new key entirely"}
json_2 = JSON.generate(hash_2)
patch = JsonDiff.generate(hash_1, hash_2)
# => [
# {:op=>:replace, :path=>"/a/b", :value=>"new key"},
# {:op=>:add, :path=>"/a/b2", :value=>"sexier key"},
# {:op=>:replace, :path=>"/c/0", :value=>2},
# {:op=>:replace, :path=>"/c/1", :value=>3},
# {:op=>:replace, :path=>"/c/2", :value=>4},
# {:op=>:add, :path=>"/d", :value=>"a new key entirely"},
# {:op=>:remove, :path=>"/x"}
# ]
json_patch = JSON.generate(patch)
JSON.patch(json_1,json_patch) == json_2
# => true
end
puts "TEST 1 Passed: #{test_1}"
def test_2
docs = [
{ },
{ key1: "value1" },
{ key1: "value1", key2: [1,2,3] },
{ key1: "value1", key2: [1,3], key3: "value3" },
{ key2: [1,2,3], key3: "value3" },
{ key2: [1,2,3], key3: "value3", key4: "value4" }
]
patches = [
(JsonDiff.generate(docs[-1],docs[-2])),
(JsonDiff.generate(docs[-2],docs[-3])),
(JsonDiff.generate(docs[-3],docs[-4])),
(JsonDiff.generate(docs[-4],docs[-5])),
(JsonDiff.generate(docs[-5],docs[-6]))
]
start_doc = docs.last
end_doc = docs.first
patched_doc = patches.inject(start_doc) do |doc, patch|
json_doc = JSON.generate doc
json_patch = JSON.generate patch
puts
puts "Applying patch to JSON:"
puts "Doc:\t#{json_doc}"
puts "Patch:\t#{json_patch}"
new_doc = JSON.patch(json_doc, json_patch)
puts "Result:\t#{new_doc}"
puts
JSON.parse(new_doc)
end
end_doc == patched_doc
end
puts "TEST 2 Passed: #{test_2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment