Hacklog: Blogamundo — poking holes in the language barrier since approximately 1 month from now

b
l
o
g
a
m
u
n
d
o

Ruby to JSON regex

Written by Jonas Galvez, 2 years, 7 months ago.
Tags: , , , , .

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]

No Comments for 'Ruby to JSON regex'

No comments yet.

Leave a comment

(required)

(required)

Comment moderation may delay the posting of your comment. XHTML: You can use the following tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <img src="" alt=""> <strike> <strong> . Don't forget to close them after use.