Skip to content

Instantly share code, notes, and snippets.

@chipp
Last active May 11, 2016 15:52
Show Gist options
  • Save chipp/c60978bc23d84913054fd8387b9d7838 to your computer and use it in GitHub Desktop.
Save chipp/c60978bc23d84913054fd8387b9d7838 to your computer and use it in GitHub Desktop.
objectify.rb
#!/Users/chipp/.rvm/bin/rvm-auto-ruby
require 'json'
IDENT = " "
def objectify(json, comma: false, newline: true, ident_level: 0)
terminator = (comma ? "," : "") + (newline ? "\n" : "")
case json
when Hash
root_identation = IDENT * ident_level
s = "@{\n"
s += json.map do |k,v|
comma = !(k == json.keys.last)
identation = IDENT * (ident_level + 1)
identation + %Q{#{ objectify(k, newline: false) } : #{ objectify(v, comma: comma, ident_level: ident_level + 1) }}
end.join
s += root_identation + "}" + terminator
when Array
root_identation = IDENT * ident_level
if json.count < 2
s = "@["
unless json.first.nil?
s += objectify(json.first, ident_level: ident_level, newline: false)
end
s += "]" + terminator
else
s = "@[\n"
s += json.map do |v, i|
comma = !(v == json.last)
identation = IDENT * (ident_level + 1)
identation + objectify(v, comma: comma, ident_level: ident_level + 1)
end.join
s += root_identation + "]" + terminator
return s
end
when String
return "@#{json.inspect}" + terminator
when Integer
return "@#{json}" + terminator
when TrueClass, FalseClass
return (json ? "@YES" : "@NO") + terminator
when NilClass
return "[NSNull null]" + terminator
else
puts json.class
end
end
json = JSON.parse STDIN.gets
print objectify(json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment