DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Quick And Dirty JSON Serializer

04.15.2007
| 5383 views |
  • submit to reddit
        // quick and dirty JOSN serializer

def jsonize(d)
  def surround(d, i=0); '' << '"[{'[i] << d << '"]}'[i]; end
  alias j jsonize; alias s surround
  if d.kind_of?(String) then s(d)
  elsif d.kind_of?(Symbol) then s(d.to_s)
  elsif d.kind_of?(Array) then s(d.collect {|v| j(v)}.join(', '), 1)
  elsif d.kind_of?(Hash) then s(d.to_a.collect { |v| "#{j(v[0])} : #{j(v[1])}" }.join(', '),2)
  # add support for other types of objects here if needed...
  else d.to_s; end
end