Issues with JSON.generate()

This took me some time to figure out — and I’m still not entirely sure what the whole issue is about. But I figured I’d post the solution here to help anyone else, since I didn’t actually find the solution spelled out anywhere.

I wanted to do a simple JSON.generate from a Hash, because I have a class with a number of attributes and I only want to include some of them. So I didn’t want to rely on the normal to_json(). Instead, I added my own json_data() method, created a Hash, and then called JSON.generate(the_hash). Unfortunately, that gave me the following error:

NoMethodError: undefined method `[]' for #<JSON::Ext::Generator::State:0x1056ba2f0>
	from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/json/encoders/hash.rb:45:in `as_json'
	from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/json/encoders/hash.rb:34:in `to_json'
	from /Library/Ruby/Gems/1.8/gems/json-1.2.0/lib/json/common.rb:183:in `generate'

I got the same error regardless of whether I had the json_pure gem or the json gem installed (I tried both). I then happened to notice a mention on the JSON rubyforge page about enforcing a specific JSON variant, which reminded me of something I read elsewhere. So I figured okay, what the hell, and I added require 'json/pure' and…voila! Problem gone. I could see from the error that the default variant (I’m running Rails 2.3.5 right now) was json/ext, which for whatever reason wasn’t working properly. Why that is, I’m not yet sure.

In any case, it works now, and perhaps this will help someone else out.

Leave a comment