tags:

views:

1218

answers:

4

Silly question, but I'm unable to figure out..

I tried the following in Ruby:

irb(main):020:0> JSON.load('[1,2,3]').class => Array

This seems to work. While neither

JSON.load('1').class

nor this

JSON.load('{1}').class

works. Any ideas?

+1  A: 

I'd say it's a bug:

>> JSON.parse(1.to_json)
JSON::ParserError: A JSON text must at least contain two octets!
     from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `initialize'
     from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `new'
     from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `parse'
     from (irb):7

I assume you're using this: (http://json.rubyforge.org/)

yes I used http://json.rubyforge.org/
Nils
+6  A: 

I'd ask the guys who programmed the library. AFAIK, 1 isn't a valid JSON object, and neither is {1} but 1 is what the library itself generates for the fixnum 1.

You'd need to do: {"number" : 1} to be valid json. The bug is that

a != JSON.parse(JSON.generate(a))
humm I'dont exactly get it. The object returned by JSON.parse(JSON.generate(a)) should not be the same object as a, but it should have the identical content. In this case does == or != compare the contents (obj#hash) or the reference?
Nils
Ruby isn't Java! The semantics of `==` are different, it *may* compare references (Object.== does) but it's typically overridden to provide sematic comparison. Ruby has .equal? to check for identical objects.
A: 

The first example is valid. The second two are not valid JSON data. go to json.org for details.

Jacob
A: 

As said only arrays and objects are allowed at the top level of JSON.

Maybe wrapping your values in an array will solve your problem.

def set( value ); @data = [value].to_json; end
def get; JSON.parse( @data )[0]; end
Peder