1
    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 `<top (required)>'
    from script/rails:41:in `require'
    from script/rails:41:in `<main>'

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.

2 Answers 2

2

In the JSON RFC, we have the statement

A JSON text is a serialized object or array.

That pretty much sums it up. At the top level, your JSON must be one of array or object.

Can your code simply do something like:

json = {'myprotocol' => whatever}.to_json
result = JSON.parse(json)['myprotocol']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that code works. Thus its up to my code to take the output of to_json and package it up nicely. Using ActiveSupport::JSON.decode as suggested by Serge is a much nicer way to do this (for me).
1

It's not the JSON you're looking for. Try this:

ActiveSupport::JSON.decode('abc'.to_json)
ActiveSupport::JSON.decode(1.to_json)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.