Ruby to JSON regex
JSON is valid YAML, valid Python, but not… valid Ruby. That’s a bummer. Fortunately, Ruby’s object notation is very close to JSON, and with the help of inspect() and a couple of most-likely-not-so-smart regular expressions, you can convert a simple Ruby object into JSON with 2 lines of code:
def ruby_to_json(obj)
json = obj.inspect.gsub(/(^|([^\\]\"|[\]]|=>\d+), ):[a-z]\w+\=\>/i) { |m| m.sub(/:(\w+)/) { |m| \"\\"#{m[1..-1]}\\"\" } }
json.gsub(/(?:=>)(?=(\"{1}|[\[](?=(\"{1}|[\[]|\d+, \\"))|\d+(, \\"|\})))/, \": \")
end
That might have been a little too much for my regex skills, so watch out. You’ll notice I’m not using negative look-behinds, but that’s because Ruby has still no support for them (Ruby 1.9 only). [Update: I posted a new implementation using a much safer technique]
