Skip to content

Instantly share code, notes, and snippets.

@sparrovv
Created January 31, 2017 21:20
Show Gist options
  • Save sparrovv/f01768578220ec954f58f6e0470db395 to your computer and use it in GitHub Desktop.
Save sparrovv/f01768578220ec954f58f6e0470db395 to your computer and use it in GitHub Desktop.
Convert json files that include $uuid node
#!/usr/bin/env ruby
require 'json'
def uuid_to_hex(uuid)
hex = uuid.gsub(/[{}-]/, "")
msb = hex[0,16]
lsb = hex[16,16]
msb = msb[14, 2] + msb[12, 2] + msb[10, 2] + msb[8, 2] + msb[6, 2] + msb[4, 2] + msb[2, 2] + msb[0, 2]
lsb = lsb[14, 2] + lsb[12, 2] + lsb[10, 2] + lsb[8, 2] + lsb[6, 2] + lsb[4, 2] + lsb[2, 2] + lsb[0, 2]
msb + lsb
end
def hex_to_base64_digest(hexdigest)
[[hexdigest].pack("H*")].pack("m0")
end
def find_uuid_node_and_replace(hash)
hash.inject({}) do |n, (k,v)|
if v.is_a? Enumerable
n[k] = find_uuid_node_and_replace(v)
else
if k == "$uuid"
n["$binary"] = hex_to_base64_digest(uuid_to_hex(v))
n["$type"] = "03"
else
n[k] = v
end
end
n
end
end
ARGF.each do |line|
object = JSON.parse(line)
puts find_uuid_node_and_replace(object).to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment