JSON object for integer

Stupid question, but I can’t understand.

I tried the following in Ruby:

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

It seems to work. Although neither

 JSON.load('1').class 

and

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

works. Any ideas?

+4
source share
6 answers

I would ask the guys who programmed the library. AFAIK, 1 not a valid JSON object, and is not {1} , but 1 is what the library itself generates for fixnum 1.

You will need: {"number" : 1} be a valid json. The error is that

 a != JSON.parse(JSON.generate(a)) 
+6
source

I would say that this is a mistake:

 >> 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 are using this: ( http://json.rubyforge.org/ )

+3
source

JSON only supports objects, just not true - json.org also does not offer this imo. it was derived from javascript, and therefore especially strings and numbers are also valid JSON:

 var json_string = "1"; var p = eval('(' + json_string + ')'); console.log(p); // => 1 typeof p // => "number" 

ActiveSupport::JSON correctly understands the original JSON value:

 require 'active_support/json' p = ActiveSupport::JSON.decode '1' # => 1 p.class # => Fixnum 

as well as MultiJson :

 require 'multi_json' p = MultiJson.load '1' # => 1 p.class # => Fixnum 

therefore, as mentioned in a2800276, this should be a mistake.


but at the time of this writing, Ruby 2 JSON was using quirks_mode by default when using the load method.

 require 'json' p = JSON.load '1' # => 1 p.class # => Fixnum 
+2
source

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

+1
source

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

Perhaps moving your values ​​to an array will solve your problem.

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

From the very foundation that JSON is:

  • JSON data types can be:
    • number
    • Line
    • Json Object ... (and a few more)

Link to a complete list of Json data types

  • Now any Json data should be encapsulated in the "Json Object" at the top level.
  • To understand why this is so, you can see that without a Json Object at the top level, everything will be free, and you can only have one of the data types in all of Json. those. number, string, array, null value, etc., but only one.
  • The Json Object type has a fixed format for the key: value pair.
  • You cannot save only the value. Thus, you cannot have something like {1}. You need to enter the correct format, i.e. "Key": a pair of "value".
0
source

All Articles