Cannot Convert String and Fixnum to JSON in Rails 3-Collection of common programming errors

    JSON.parse('abc'.to_json) gives this error (in rails):

    JSON::ParserError: 757: unexpected token at '"abc"'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/json-1.7.4/lib/json/common.rb:155:in `parse'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/json-1.7.4/lib/json/common.rb:155:in `parse'
    from (irb):20
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands.rb:40:in `'
    from script/rails:41:in `require'
    from script/rails:41:in `'

Likewise this fails:

 JSON.parse(100.to_json)

And this too (with a slightly different error):

 JSON.parse(1.to_json)

Why dont I just wrap the outputted json in {} to make it look like real json? Because I’m writing code that should be able to take any object and serialize it as JSON and pull it back out again.

I think the issue comes from this: JSON looks like a set of encoded key-value pairs all put within {}. But the to_json methods in rails (3.x) don’t output any {} at all.

Given that, all I really want is an easy way to serialize arbitrary ruby/rails objects into strings and back again. Already, many objects have a to_json method (String, Fixnum, Array, Hash) but the String and Fixnum versions don’t produce Json that can be parsed.