json 2.3.0 → 2.3.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -4,12 +4,15 @@ require 'json/generic_object'
4
4
 
5
5
  module JSON
6
6
  class << self
7
- # If _object_ is string-like, parse the string and return the parsed
8
- # result as a Ruby data structure. Otherwise generate a JSON text from the
9
- # Ruby data structure object and return it.
7
+ # If +object+ is a
8
+ # {String-convertible object}[doc/implicit_conversion_rdoc.html#label-String-Convertible+Objects]
9
+ # (implementing +to_str+), calls JSON.parse with +object+ and +opts+:
10
+ # json = '[0, 1, null]'
11
+ # JSON[json]# => [0, 1, nil]
10
12
  #
11
- # The _opts_ argument is passed through to generate/parse respectively.
12
- # See generate and parse for their documentation.
13
+ # Otherwise, calls JSON.generate with +object+ and +opts+:
14
+ # ruby = [0, 1, nil]
15
+ # JSON[ruby] # => '[0,1,null]'
13
16
  def [](object, opts = {})
14
17
  if object.respond_to? :to_str
15
18
  JSON.parse(object.to_str, opts)
@@ -19,7 +22,8 @@ module JSON
19
22
  end
20
23
 
21
24
  # Returns the JSON parser class that is used by JSON. This is either
22
- # JSON::Ext::Parser or JSON::Pure::Parser.
25
+ # JSON::Ext::Parser or JSON::Pure::Parser:
26
+ # JSON.parser # => JSON::Ext::Parser
23
27
  attr_reader :parser
24
28
 
25
29
  # Set the JSON parser class _parser_ to be used by JSON.
@@ -84,15 +88,18 @@ module JSON
84
88
  end
85
89
 
86
90
  # Returns the JSON generator module that is used by JSON. This is
87
- # either JSON::Ext::Generator or JSON::Pure::Generator.
91
+ # either JSON::Ext::Generator or JSON::Pure::Generator:
92
+ # JSON.generator # => JSON::Ext::Generator
88
93
  attr_reader :generator
89
94
 
90
- # Returns the JSON generator state class that is used by JSON. This is
91
- # either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
95
+ # Sets or Returns the JSON generator state class that is used by JSON. This is
96
+ # either JSON::Ext::Generator::State or JSON::Pure::Generator::State:
97
+ # JSON.state # => JSON::Ext::Generator::State
92
98
  attr_accessor :state
93
99
 
94
- # This is create identifier, which is used to decide if the _json_create_
95
- # hook of a class should be called. It defaults to 'json_class'.
100
+ # Sets or returns create identifier, which is used to decide if the _json_create_
101
+ # hook of a class should be called; initial value is +json_class+:
102
+ # JSON.create_id # => 'json_class'
96
103
  attr_accessor :create_id
97
104
  end
98
105
  self.create_id = 'json_class'
@@ -126,7 +133,7 @@ module JSON
126
133
  # This exception is raised if a generator or unparser error occurs.
127
134
  class GeneratorError < JSONError; end
128
135
  # For backwards compatibility
129
- UnparserError = GeneratorError
136
+ UnparserError = GeneratorError # :nodoc:
130
137
 
131
138
  # This exception is raised if the required unicode support is missing on the
132
139
  # system. Usually this means that the iconv library is not installed.
@@ -134,43 +141,139 @@ module JSON
134
141
 
135
142
  module_function
136
143
 
137
- # Parse the JSON document _source_ into a Ruby data structure and return it.
138
- #
139
- # _opts_ can have the following
140
- # keys:
141
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
142
- # structures. Disable depth checking with :max_nesting => false. It
143
- # defaults to 100.
144
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
145
- # defiance of RFC 7159 to be parsed by the Parser. This option defaults
146
- # to false.
147
- # * *symbolize_names*: If set to true, returns symbols for the names
148
- # (keys) in a JSON object. Otherwise strings are returned. Strings are
149
- # the default.
150
- # * *create_additions*: If set to false, the Parser doesn't create
151
- # additions even if a matching class and create_id was found. This option
152
- # defaults to false.
153
- # * *object_class*: Defaults to Hash
154
- # * *array_class*: Defaults to Array
144
+ # :call-seq:
145
+ # JSON.parse(source, opts) -> object
146
+ #
147
+ # Argument +source+ contains the \String to be parsed. It must be a
148
+ # {String-convertible object}[doc/implicit_conversion_rdoc.html#label-String-Convertible+Objects]
149
+ # (implementing +to_str+), and must contain valid \JSON data.
150
+ #
151
+ # Argument +opts+, if given, contains options for the parsing, and must be a
152
+ # {Hash-convertible object}[doc/implicit_conversion_rdoc.html#label-Hash-Convertible+Objects]
153
+ # (implementing +to_hash+).
154
+ #
155
+ # Returns the Ruby objects created by parsing the given +source+.
156
+ #
157
+ # ---
158
+ #
159
+ # When +source+ is a \JSON array, returns a Ruby \Array:
160
+ # source = '["foo", 1.0, true, false, null]'
161
+ # ruby = JSON.parse(source)
162
+ # ruby # => ["foo", 1.0, true, false, nil]
163
+ # ruby.class # => Array
164
+ #
165
+ # When +source+ is a \JSON object, returns a Ruby \Hash:
166
+ # source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
167
+ # ruby = JSON.parse(source)
168
+ # ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
169
+ # ruby.class # => Hash
170
+ #
171
+ # For examples of parsing for all \JSON data types, see
172
+ # {Parsing \JSON}[#module-JSON-label-Parsing+JSON].
173
+ #
174
+ # ====== Input Options
175
+ #
176
+ # Option +max_nesting+ (\Integer) specifies the maximum nesting depth allowed;
177
+ # defaults to +100+; specify +false+ to disable depth checking.
178
+ #
179
+ # With the default, +false+:
180
+ # source = '[0, [1, [2, [3]]]]'
181
+ # ruby = JSON.parse(source)
182
+ # ruby # => [0, [1, [2, [3]]]]
183
+ # Too deep:
184
+ # # Raises JSON::NestingError (nesting of 2 is too deep):
185
+ # JSON.parse(source, {max_nesting: 1})
186
+ # Bad value:
187
+ # # Raises TypeError (wrong argument type Symbol (expected Fixnum)):
188
+ # JSON.parse(source, {max_nesting: :foo})
189
+ #
190
+ # ---
191
+ #
192
+ # Option +allow_nan+ (boolean) specifies whether to allow
193
+ # NaN, Infinity, and MinusInfinity in +source+;
194
+ # defaults to +false+.
195
+ #
196
+ # With the default, +false+:
197
+ # # Raises JSON::ParserError (225: unexpected token at '[NaN]'):
198
+ # JSON.parse('[NaN]')
199
+ # # Raises JSON::ParserError (232: unexpected token at '[Infinity]'):
200
+ # JSON.parse('[Infinity]')
201
+ # # Raises JSON::ParserError (248: unexpected token at '[-Infinity]'):
202
+ # JSON.parse('[-Infinity]')
203
+ # Allow:
204
+ # source = '[NaN, Infinity, -Infinity]'
205
+ # ruby = JSON.parse(source, {allow_nan: true})
206
+ # ruby # => [NaN, Infinity, -Infinity]
207
+ #
208
+ # ====== Output Options
209
+ #
210
+ # Option +symbolize_names+ (boolean) specifies whether returned \Hash keys
211
+ # should be Symbols;
212
+ # defaults to +false+ (use Strings).
213
+ #
214
+ # With the default, +false+:
215
+ # source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
216
+ # ruby = JSON.parse(source)
217
+ # ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
218
+ # Use Symbols:
219
+ # ruby = JSON.parse(source, {symbolize_names: true})
220
+ # ruby # => {:a=>"foo", :b=>1.0, :c=>true, :d=>false, :e=>nil}
221
+ #
222
+ # ---
223
+ #
224
+ # Option +object_class+ (\Class) specifies the Ruby class to be used
225
+ # for each \JSON object;
226
+ # defaults to \Hash.
227
+ #
228
+ # With the default, \Hash:
229
+ # source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
230
+ # ruby = JSON.parse(source)
231
+ # ruby.class # => Hash
232
+ # Use class \OpenStruct:
233
+ # ruby = JSON.parse(source, {object_class: OpenStruct})
234
+ # ruby # => #<OpenStruct a="foo", b=1.0, c=true, d=false, e=nil>
235
+ #
236
+ # ---
237
+ #
238
+ # Option +array_class+ (\Class) specifies the Ruby class to be used
239
+ # for each \JSON array;
240
+ # defaults to \Array.
241
+ #
242
+ # With the default, \Array:
243
+ # source = '["foo", 1.0, true, false, null]'
244
+ # ruby = JSON.parse(source)
245
+ # ruby.class # => Array
246
+ # Use class \Set:
247
+ # ruby = JSON.parse(source, {array_class: Set})
248
+ # ruby # => #<Set: {"foo", 1.0, true, false, nil}>
249
+ #
250
+ # ---
251
+ #
252
+ # Option +create_additions+ (boolean) specifies whether to use \JSON additions in parsing.
253
+ # See {\JSON Additions}[#module-JSON-label-JSON+Additions].
254
+ #
255
+ # ====== Exceptions
256
+ #
257
+ # Raises an exception if +source+ is not valid JSON:
258
+ #
259
+ # # Raises JSON::ParserError (783: unexpected token at ''):
260
+ # JSON.parse('')
261
+ #
155
262
  def parse(source, opts = {})
156
263
  Parser.new(source, **(opts||{})).parse
157
264
  end
158
265
 
159
- # Parse the JSON document _source_ into a Ruby data structure and return it.
160
- # The bang version of the parse method defaults to the more dangerous values
161
- # for the _opts_ hash, so be sure only to parse trusted _source_ documents.
162
- #
163
- # _opts_ can have the following keys:
164
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
165
- # structures. Enable depth checking with :max_nesting => anInteger. The
166
- # parse! methods defaults to not doing max depth checking: This can be
167
- # dangerous if someone wants to fill up your stack.
168
- # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
169
- # defiance of RFC 7159 to be parsed by the Parser. This option defaults
170
- # to true.
171
- # * *create_additions*: If set to false, the Parser doesn't create
172
- # additions even if a matching class and create_id was found. This option
173
- # defaults to false.
266
+ # :call-seq:
267
+ # JSON.parse!(source, opts) -> object
268
+ #
269
+ # Calls
270
+ # parse(source, opts)
271
+ # with +source+ and possibly modified +opts+.
272
+ #
273
+ # Differences from JSON.parse:
274
+ # - Option +max_nesting+, if not provided, defaults to +false+,
275
+ # which disables checking for nesting depth.
276
+ # - Option +allow_nan+, if not provided, defaults to +true+.
174
277
  def parse!(source, opts = {})
175
278
  opts = {
176
279
  :max_nesting => false,
@@ -179,32 +282,135 @@ module JSON
179
282
  Parser.new(source, **(opts||{})).parse
180
283
  end
181
284
 
182
- # Generate a JSON document from the Ruby data structure _obj_ and return
183
- # it. _state_ is * a JSON::State object,
184
- # * or a Hash like object (responding to to_hash),
185
- # * an object convertible into a hash by a to_h method,
186
- # that is used as or to configure a State object.
187
- #
188
- # It defaults to a state object, that creates the shortest possible JSON text
189
- # in one line, checks for circular data structures and doesn't allow NaN,
190
- # Infinity, and -Infinity.
191
- #
192
- # A _state_ hash can have the following keys:
193
- # * *indent*: a string used to indent levels (default: ''),
194
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
195
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
196
- # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
197
- # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
198
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
199
- # generated, otherwise an exception is thrown if these values are
200
- # encountered. This options defaults to false.
201
- # * *max_nesting*: The maximum depth of nesting allowed in the data
202
- # structures from which JSON is to be generated. Disable depth checking
203
- # with :max_nesting => false, it defaults to 100.
204
- #
205
- # See also the fast_generate for the fastest creation method with the least
206
- # amount of sanity checks, and the pretty_generate method for some
207
- # defaults for pretty output.
285
+ # :call-seq:
286
+ # JSON.generate(obj, opts = nil) -> new_string
287
+ #
288
+ # Argument +obj+ is the Ruby object to be converted to \JSON.
289
+ #
290
+ # Argument +opts+, if given, contains options for the generation, and must be a
291
+ # {Hash-convertible object}[doc/implicit_conversion_rdoc.html#label-Hash-Convertible+Objects]
292
+ # (implementing +to_hash+).
293
+ #
294
+ # Returns a \String containing the generated \JSON data.
295
+ #
296
+ # See also JSON.fast_generate, JSON.pretty_generate.
297
+ #
298
+ # ---
299
+ #
300
+ # When +obj+ is an
301
+ # {Array-convertible object}[doc/implicit_conversion_rdoc.html#label-Array-Convertible+Objects]
302
+ # (implementing +to_ary+), returns a \String containing a \JSON array:
303
+ # obj = ["foo", 1.0, true, false, nil]
304
+ # json = JSON.generate(obj)
305
+ # json # => '["foo",1.0,true,false,null]'
306
+ #
307
+ # When +obj+ is a
308
+ # {Hash-convertible object}[doc/implicit_conversion_rdoc.html#label-Hash-Convertible+Objects],
309
+ # return a \String containing a \JSON object:
310
+ # obj = {foo: 0, bar: 's', baz: :bat}
311
+ # json = JSON.generate(obj)
312
+ # json # => '{"foo":0,"bar":"s","baz":"bat"}'
313
+ #
314
+ # For examples of generating from other Ruby objects, see
315
+ # {Generating \JSON from Other Objects}[#module-JSON-label-Generating+JSON+from+Other+Objects].
316
+ #
317
+ # ====== Input Options
318
+ #
319
+ # Option +allow_nan+ (boolean) specifies whether
320
+ # +NaN+, +Infinity+, and <tt>-Infinity</tt> may be generated;
321
+ # defaults to +false+.
322
+ #
323
+ # With the default, +false+:
324
+ # # Raises JSON::GeneratorError (920: NaN not allowed in JSON):
325
+ # JSON.generate(JSON::NaN)
326
+ # # Raises JSON::GeneratorError (917: Infinity not allowed in JSON):
327
+ # JSON.generate(JSON::Infinity)
328
+ # # Raises JSON::GeneratorError (917: -Infinity not allowed in JSON):
329
+ # JSON.generate(JSON::MinusInfinity)
330
+ #
331
+ # Allow:
332
+ # ruby = [Float::NaN, Float::Infinity, Float::MinusInfinity]
333
+ # JSON.generate(ruby, allow_nan: true) # => '[NaN,Infinity,-Infinity]'
334
+ #
335
+ # ---
336
+ #
337
+ # Option +max_nesting+ (\Integer) specifies the maximum nesting depth
338
+ # in +obj+; defaults to +100+.
339
+ #
340
+ # With the default, +100+:
341
+ # obj = [[[[[[0]]]]]]
342
+ # JSON.generate(obj) # => '[[[[[[0]]]]]]'
343
+ #
344
+ # Too deep:
345
+ # # Raises JSON::NestingError (nesting of 2 is too deep):
346
+ # JSON.generate(obj, max_nesting: 2)
347
+ #
348
+ # ====== Output Options
349
+ #
350
+ # The default formatting options generate the most compact
351
+ # \JSON data, all on one line and with no whitespace.
352
+ #
353
+ # You can use these formatting options to generate
354
+ # \JSON data in a more open format, using whitespace.
355
+ # See also JSON.pretty_generate.
356
+ #
357
+ # - Option +array_nl+ (\String) specifies a string (usually a newline)
358
+ # to be inserted after each \JSON array; defaults to the empty \String, <tt>''</tt>.
359
+ # - Option +object_nl+ (\String) specifies a string (usually a newline)
360
+ # to be inserted after each \JSON object; defaults to the empty \String, <tt>''</tt>.
361
+ # - Option +indent+ (\String) specifies the string (usually spaces) to be
362
+ # used for indentation; defaults to the empty \String, <tt>''</tt>;
363
+ # defaults to the empty \String, <tt>''</tt>;
364
+ # has no effect unless options +array_nl+ or +object_nl+ specify newlines.
365
+ # - Option +space+ (\String) specifies a string (usually a space) to be
366
+ # inserted after the colon in each \JSON object's pair;
367
+ # defaults to the empty \String, <tt>''</tt>.
368
+ # - Option +space_before+ (\String) specifies a string (usually a space) to be
369
+ # inserted before the colon in each \JSON object's pair;
370
+ # defaults to the empty \String, <tt>''</tt>.
371
+ #
372
+ # In this example, +obj+ is used first to generate the shortest
373
+ # \JSON data (no whitespace), then again with all formatting options
374
+ # specified:
375
+ #
376
+ # obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
377
+ # json = JSON.generate(obj)
378
+ # puts 'Compact:', json
379
+ # opts = {
380
+ # array_nl: "\n",
381
+ # object_nl: "\n",
382
+ # indent+: ' ',
383
+ # space_before: ' ',
384
+ # space: ' '
385
+ # }
386
+ # puts 'Open:', JSON.generate(obj, opts)
387
+ #
388
+ # Output:
389
+ # Compact:
390
+ # {"foo":["bar","baz"],"bat":{"bam":0,"bad":1}}
391
+ # Open:
392
+ # {
393
+ # "foo" : [
394
+ # "bar",
395
+ # "baz"
396
+ # ],
397
+ # "bat" : {
398
+ # "bam" : 0,
399
+ # "bad" : 1
400
+ # }
401
+ # }
402
+ #
403
+ # ---
404
+ #
405
+ # Raises an exception if any formatting option is not a \String.
406
+ #
407
+ # ====== Exceptions
408
+ #
409
+ # Raises an exception if +obj+ contains circular references:
410
+ # a = []; b = []; a.push(b); b.push(a)
411
+ # # Raises JSON::NestingError (nesting of 100 is too deep):
412
+ # JSON.generate(a)
413
+ #
208
414
  def generate(obj, opts = nil)
209
415
  if State === opts
210
416
  state, opts = opts, nil
@@ -231,11 +437,16 @@ module JSON
231
437
  module_function :unparse
232
438
  # :startdoc:
233
439
 
234
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
235
- # This method disables the checks for circles in Ruby objects.
440
+ # Arguments +obj+ and +opts+ here are the same as
441
+ # arguments +obj+ and +opts+ in JSON.generate.
442
+ #
443
+ # By default, generates \JSON data without checking
444
+ # for circular references in +obj+ (option +max_nesting+ set to +false+, disabled).
236
445
  #
237
- # *WARNING*: Be careful not to pass any Ruby data structures with circles as
238
- # _obj_ argument because this will cause JSON to go into an infinite loop.
446
+ # Raises an exception if +obj+ contains circular references:
447
+ # a = []; b = []; a.push(b); b.push(a)
448
+ # # Raises SystemStackError (stack level too deep):
449
+ # JSON.fast_generate(a)
239
450
  def fast_generate(obj, opts = nil)
240
451
  if State === opts
241
452
  state, opts = opts, nil
@@ -261,12 +472,36 @@ module JSON
261
472
  module_function :fast_unparse
262
473
  # :startdoc:
263
474
 
264
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
265
- # The returned document is a prettier form of the document returned by
266
- # #unparse.
475
+ # :call-seq:
476
+ # JSON.pretty_generate(obj, opts = nil) -> new_string
477
+ #
478
+ # Arguments +obj+ and +opts+ here are the same as
479
+ # arguments +obj+ and +opts+ in JSON.generate.
480
+ #
481
+ # Default options are:
482
+ # {
483
+ # indent: ' ', # Two spaces
484
+ # space: ' ', # One space
485
+ # array_nl: "\n", # Newline
486
+ # object_nl: "\n" # Newline
487
+ # }
488
+ #
489
+ # Example:
490
+ # obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
491
+ # json = JSON.pretty_generate(obj)
492
+ # puts json
493
+ # Output:
494
+ # {
495
+ # "foo": [
496
+ # "bar",
497
+ # "baz"
498
+ # ],
499
+ # "bat": {
500
+ # "bam": 0,
501
+ # "bad": 1
502
+ # }
503
+ # }
267
504
  #
268
- # The _opts_ argument can be used to configure the generator. See the
269
- # generate method for a more detailed explanation.
270
505
  def pretty_generate(obj, opts = nil)
271
506
  if State === opts
272
507
  state, opts = opts, nil
@@ -293,10 +528,10 @@ module JSON
293
528
  # :startdoc:
294
529
 
295
530
  class << self
296
- # The global default options for the JSON.load method:
297
- # :max_nesting: false
298
- # :allow_nan: true
299
- # :allow_blank: true
531
+ # Sets or returns default options for the JSON.load method.
532
+ # Initially:
533
+ # opts = JSON.load_default_options
534
+ # opts # => {:max_nesting=>false, :allow_nan=>true, :allow_blank=>true, :create_additions=>true}
300
535
  attr_accessor :load_default_options
301
536
  end
302
537
  self.load_default_options = {
@@ -355,10 +590,10 @@ module JSON
355
590
  module_function :restore
356
591
 
357
592
  class << self
358
- # The global default options for the JSON.dump method:
359
- # :max_nesting: false
360
- # :allow_nan: true
361
- # :allow_blank: true
593
+ # Sets or returns the default options for the JSON.dump method.
594
+ # Initially:
595
+ # opts = JSON.dump_default_options
596
+ # opts # => {:max_nesting=>false, :allow_nan=>true}
362
597
  attr_accessor :dump_default_options
363
598
  end
364
599
  self.dump_default_options = {
@@ -402,7 +637,7 @@ module JSON
402
637
  raise ArgumentError, "exceed depth limit"
403
638
  end
404
639
 
405
- # Encodes string using Ruby's _String.encode_
640
+ # Encodes string using String.encode.
406
641
  def self.iconv(to, from, string)
407
642
  string.encode(to, from)
408
643
  end