Make Love not War

Rails JSON fun

May 28th 2009

Well having multiple JSON parsers in Ruby on Rails 2 is not a lot of fun.

Let me explain the situation. I was happily using “.to_json” (means Rails JSON parser) until I had to parse a POST request with JSON body. I googled it like normal people do and found this:

require "json"
data = JSON.parse(input)

which worked fine until I tried my Open Flash Charts. They were blank. No error message. Nothing. Removing the statement to require JSON fixed the issue.

I also tried

require "json/pure"

and

require "json/ext"

with similar results.

The short debugging session revealed that Ruby Open Flash Chart 2 helper is generating right JSON when Rails built-in generator is used. When using json, json/pure or json/ext the certain characters (slashes, quotes) in a resulting string were escaped (sometimes several times) which breaks the Open Flash Charts.

The solution was to use

data = ActiveSupport::JSON.decode(input)

which is a call to parse the json string using the Rails built-in parser.

blog comments powered by Disqus