json_pure 2.7.5 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/json/common.rb DELETED
@@ -1,734 +0,0 @@
1
- #frozen_string_literal: true
2
- require 'json/version'
3
-
4
- module JSON
5
- autoload :GenericObject, 'json/generic_object'
6
-
7
- NOT_SET = Object.new.freeze
8
- private_constant :NOT_SET
9
-
10
- class << self
11
- # :call-seq:
12
- # JSON[object] -> new_array or new_string
13
- #
14
- # If +object+ is a \String,
15
- # calls JSON.parse with +object+ and +opts+ (see method #parse):
16
- # json = '[0, 1, null]'
17
- # JSON[json]# => [0, 1, nil]
18
- #
19
- # Otherwise, calls JSON.generate with +object+ and +opts+ (see method #generate):
20
- # ruby = [0, 1, nil]
21
- # JSON[ruby] # => '[0,1,null]'
22
- def [](object, opts = {})
23
- if object.is_a?(String)
24
- return JSON.parse(object, opts)
25
- elsif object.respond_to?(:to_str)
26
- str = object.to_str
27
- if str.is_a?(String)
28
- return JSON.parse(object.to_str, opts)
29
- end
30
- end
31
-
32
- JSON.generate(object, opts)
33
- end
34
-
35
- # Returns the JSON parser class that is used by JSON. This is either
36
- # JSON::Ext::Parser or JSON::Pure::Parser:
37
- # JSON.parser # => JSON::Ext::Parser
38
- attr_reader :parser
39
-
40
- # Set the JSON parser class _parser_ to be used by JSON.
41
- def parser=(parser) # :nodoc:
42
- @parser = parser
43
- remove_const :Parser if const_defined?(:Parser, false)
44
- const_set :Parser, parser
45
- end
46
-
47
- # Return the constant located at _path_. The format of _path_ has to be
48
- # either ::A::B::C or A::B::C. In any case, A has to be located at the top
49
- # level (absolute namespace path?). If there doesn't exist a constant at
50
- # the given path, an ArgumentError is raised.
51
- def deep_const_get(path) # :nodoc:
52
- path.to_s.split(/::/).inject(Object) do |p, c|
53
- case
54
- when c.empty? then p
55
- when p.const_defined?(c, true) then p.const_get(c)
56
- else
57
- begin
58
- p.const_missing(c)
59
- rescue NameError => e
60
- raise ArgumentError, "can't get const #{path}: #{e}"
61
- end
62
- end
63
- end
64
- end
65
-
66
- # Set the module _generator_ to be used by JSON.
67
- def generator=(generator) # :nodoc:
68
- old, $VERBOSE = $VERBOSE, nil
69
- @generator = generator
70
- generator_methods = generator::GeneratorMethods
71
- for const in generator_methods.constants
72
- klass = deep_const_get(const)
73
- modul = generator_methods.const_get(const)
74
- klass.class_eval do
75
- instance_methods(false).each do |m|
76
- m.to_s == 'to_json' and remove_method m
77
- end
78
- include modul
79
- end
80
- end
81
- self.state = generator::State
82
- const_set :State, self.state
83
- const_set :SAFE_STATE_PROTOTYPE, State.new # for JRuby
84
- const_set :FAST_STATE_PROTOTYPE, create_fast_state
85
- const_set :PRETTY_STATE_PROTOTYPE, create_pretty_state
86
- ensure
87
- $VERBOSE = old
88
- end
89
-
90
- def create_fast_state
91
- State.new(
92
- :indent => '',
93
- :space => '',
94
- :object_nl => "",
95
- :array_nl => "",
96
- :max_nesting => false
97
- )
98
- end
99
-
100
- def create_pretty_state
101
- State.new(
102
- :indent => ' ',
103
- :space => ' ',
104
- :object_nl => "\n",
105
- :array_nl => "\n"
106
- )
107
- end
108
-
109
- # Returns the JSON generator module that is used by JSON. This is
110
- # either JSON::Ext::Generator or JSON::Pure::Generator:
111
- # JSON.generator # => JSON::Ext::Generator
112
- attr_reader :generator
113
-
114
- # Sets or Returns the JSON generator state class that is used by JSON. This is
115
- # either JSON::Ext::Generator::State or JSON::Pure::Generator::State:
116
- # JSON.state # => JSON::Ext::Generator::State
117
- attr_accessor :state
118
- end
119
-
120
- # Sets create identifier, which is used to decide if the _json_create_
121
- # hook of a class should be called; initial value is +json_class+:
122
- # JSON.create_id # => 'json_class'
123
- def self.create_id=(new_value)
124
- Thread.current[:"JSON.create_id"] = new_value.dup.freeze
125
- end
126
-
127
- # Returns the current create identifier.
128
- # See also JSON.create_id=.
129
- def self.create_id
130
- Thread.current[:"JSON.create_id"] || 'json_class'
131
- end
132
-
133
- NaN = 0.0/0
134
-
135
- Infinity = 1.0/0
136
-
137
- MinusInfinity = -Infinity
138
-
139
- # The base exception for JSON errors.
140
- class JSONError < StandardError
141
- def self.wrap(exception)
142
- obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
143
- obj.set_backtrace exception.backtrace
144
- obj
145
- end
146
- end
147
-
148
- # This exception is raised if a parser error occurs.
149
- class ParserError < JSONError; end
150
-
151
- # This exception is raised if the nesting of parsed data structures is too
152
- # deep.
153
- class NestingError < ParserError; end
154
-
155
- # :stopdoc:
156
- class CircularDatastructure < NestingError; end
157
- # :startdoc:
158
-
159
- # This exception is raised if a generator or unparser error occurs.
160
- class GeneratorError < JSONError; end
161
- # For backwards compatibility
162
- UnparserError = GeneratorError # :nodoc:
163
-
164
- # This exception is raised if the required unicode support is missing on the
165
- # system. Usually this means that the iconv library is not installed.
166
- class MissingUnicodeSupport < JSONError; end
167
-
168
- module_function
169
-
170
- # :call-seq:
171
- # JSON.parse(source, opts) -> object
172
- #
173
- # Returns the Ruby objects created by parsing the given +source+.
174
- #
175
- # Argument +source+ contains the \String to be parsed.
176
- #
177
- # Argument +opts+, if given, contains a \Hash of options for the parsing.
178
- # See {Parsing Options}[#module-JSON-label-Parsing+Options].
179
- #
180
- # ---
181
- #
182
- # When +source+ is a \JSON array, returns a Ruby \Array:
183
- # source = '["foo", 1.0, true, false, null]'
184
- # ruby = JSON.parse(source)
185
- # ruby # => ["foo", 1.0, true, false, nil]
186
- # ruby.class # => Array
187
- #
188
- # When +source+ is a \JSON object, returns a Ruby \Hash:
189
- # source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
190
- # ruby = JSON.parse(source)
191
- # ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
192
- # ruby.class # => Hash
193
- #
194
- # For examples of parsing for all \JSON data types, see
195
- # {Parsing \JSON}[#module-JSON-label-Parsing+JSON].
196
- #
197
- # Parses nested JSON objects:
198
- # source = <<-EOT
199
- # {
200
- # "name": "Dave",
201
- # "age" :40,
202
- # "hats": [
203
- # "Cattleman's",
204
- # "Panama",
205
- # "Tophat"
206
- # ]
207
- # }
208
- # EOT
209
- # ruby = JSON.parse(source)
210
- # ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
211
- #
212
- # ---
213
- #
214
- # Raises an exception if +source+ is not valid JSON:
215
- # # Raises JSON::ParserError (783: unexpected token at ''):
216
- # JSON.parse('')
217
- #
218
- def parse(source, opts = nil)
219
- if opts.nil?
220
- Parser.new(source).parse
221
- else
222
- # NB: The ** shouldn't be required, but we have to deal with
223
- # different versions of the `json` and `json_pure` gems being
224
- # loaded concurrently.
225
- # Prior to 2.7.3, `JSON::Ext::Parser` would only take kwargs.
226
- # Ref: https://github.com/ruby/json/issues/650
227
- Parser.new(source, **opts).parse
228
- end
229
- end
230
-
231
- # :call-seq:
232
- # JSON.parse!(source, opts) -> object
233
- #
234
- # Calls
235
- # parse(source, opts)
236
- # with +source+ and possibly modified +opts+.
237
- #
238
- # Differences from JSON.parse:
239
- # - Option +max_nesting+, if not provided, defaults to +false+,
240
- # which disables checking for nesting depth.
241
- # - Option +allow_nan+, if not provided, defaults to +true+.
242
- def parse!(source, opts = {})
243
- opts = {
244
- :max_nesting => false,
245
- :allow_nan => true
246
- }.merge(opts)
247
- Parser.new(source, **(opts||{})).parse
248
- end
249
-
250
- # :call-seq:
251
- # JSON.load_file(path, opts={}) -> object
252
- #
253
- # Calls:
254
- # parse(File.read(path), opts)
255
- #
256
- # See method #parse.
257
- def load_file(filespec, opts = {})
258
- parse(File.read(filespec), opts)
259
- end
260
-
261
- # :call-seq:
262
- # JSON.load_file!(path, opts = {})
263
- #
264
- # Calls:
265
- # JSON.parse!(File.read(path, opts))
266
- #
267
- # See method #parse!
268
- def load_file!(filespec, opts = {})
269
- parse!(File.read(filespec), opts)
270
- end
271
-
272
- # :call-seq:
273
- # JSON.generate(obj, opts = nil) -> new_string
274
- #
275
- # Returns a \String containing the generated \JSON data.
276
- #
277
- # See also JSON.fast_generate, JSON.pretty_generate.
278
- #
279
- # Argument +obj+ is the Ruby object to be converted to \JSON.
280
- #
281
- # Argument +opts+, if given, contains a \Hash of options for the generation.
282
- # See {Generating Options}[#module-JSON-label-Generating+Options].
283
- #
284
- # ---
285
- #
286
- # When +obj+ is an \Array, returns a \String containing a \JSON array:
287
- # obj = ["foo", 1.0, true, false, nil]
288
- # json = JSON.generate(obj)
289
- # json # => '["foo",1.0,true,false,null]'
290
- #
291
- # When +obj+ is a \Hash, returns a \String containing a \JSON object:
292
- # obj = {foo: 0, bar: 's', baz: :bat}
293
- # json = JSON.generate(obj)
294
- # json # => '{"foo":0,"bar":"s","baz":"bat"}'
295
- #
296
- # For examples of generating from other Ruby objects, see
297
- # {Generating \JSON from Other Objects}[#module-JSON-label-Generating+JSON+from+Other+Objects].
298
- #
299
- # ---
300
- #
301
- # Raises an exception if any formatting option is not a \String.
302
- #
303
- # Raises an exception if +obj+ contains circular references:
304
- # a = []; b = []; a.push(b); b.push(a)
305
- # # Raises JSON::NestingError (nesting of 100 is too deep):
306
- # JSON.generate(a)
307
- #
308
- def generate(obj, opts = nil)
309
- if State === opts
310
- state = opts
311
- else
312
- state = State.new(opts)
313
- end
314
- state.generate(obj)
315
- end
316
-
317
- # :stopdoc:
318
- # I want to deprecate these later, so I'll first be silent about them, and
319
- # later delete them.
320
- alias unparse generate
321
- module_function :unparse
322
- # :startdoc:
323
-
324
- # :call-seq:
325
- # JSON.fast_generate(obj, opts) -> new_string
326
- #
327
- # Arguments +obj+ and +opts+ here are the same as
328
- # arguments +obj+ and +opts+ in JSON.generate.
329
- #
330
- # By default, generates \JSON data without checking
331
- # for circular references in +obj+ (option +max_nesting+ set to +false+, disabled).
332
- #
333
- # Raises an exception if +obj+ contains circular references:
334
- # a = []; b = []; a.push(b); b.push(a)
335
- # # Raises SystemStackError (stack level too deep):
336
- # JSON.fast_generate(a)
337
- def fast_generate(obj, opts = nil)
338
- if State === opts
339
- state = opts
340
- else
341
- state = JSON.create_fast_state.configure(opts)
342
- end
343
- state.generate(obj)
344
- end
345
-
346
- # :stopdoc:
347
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
348
- alias fast_unparse fast_generate
349
- module_function :fast_unparse
350
- # :startdoc:
351
-
352
- # :call-seq:
353
- # JSON.pretty_generate(obj, opts = nil) -> new_string
354
- #
355
- # Arguments +obj+ and +opts+ here are the same as
356
- # arguments +obj+ and +opts+ in JSON.generate.
357
- #
358
- # Default options are:
359
- # {
360
- # indent: ' ', # Two spaces
361
- # space: ' ', # One space
362
- # array_nl: "\n", # Newline
363
- # object_nl: "\n" # Newline
364
- # }
365
- #
366
- # Example:
367
- # obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
368
- # json = JSON.pretty_generate(obj)
369
- # puts json
370
- # Output:
371
- # {
372
- # "foo": [
373
- # "bar",
374
- # "baz"
375
- # ],
376
- # "bat": {
377
- # "bam": 0,
378
- # "bad": 1
379
- # }
380
- # }
381
- #
382
- def pretty_generate(obj, opts = nil)
383
- if State === opts
384
- state, opts = opts, nil
385
- else
386
- state = JSON.create_pretty_state
387
- end
388
- if opts
389
- if opts.respond_to? :to_hash
390
- opts = opts.to_hash
391
- elsif opts.respond_to? :to_h
392
- opts = opts.to_h
393
- else
394
- raise TypeError, "can't convert #{opts.class} into Hash"
395
- end
396
- state.configure(opts)
397
- end
398
- state.generate(obj)
399
- end
400
-
401
- # :stopdoc:
402
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
403
- alias pretty_unparse pretty_generate
404
- module_function :pretty_unparse
405
- # :startdoc:
406
-
407
- class << self
408
- # Sets or returns default options for the JSON.load method.
409
- # Initially:
410
- # opts = JSON.load_default_options
411
- # opts # => {:max_nesting=>false, :allow_nan=>true, :allow_blank=>true, :create_additions=>true}
412
- attr_accessor :load_default_options
413
- end
414
- self.load_default_options = {
415
- :max_nesting => false,
416
- :allow_nan => true,
417
- :allow_blank => true,
418
- :create_additions => true,
419
- }
420
-
421
- # :call-seq:
422
- # JSON.load(source, proc = nil, options = {}) -> object
423
- #
424
- # Returns the Ruby objects created by parsing the given +source+.
425
- #
426
- # - Argument +source+ must be, or be convertible to, a \String:
427
- # - If +source+ responds to instance method +to_str+,
428
- # <tt>source.to_str</tt> becomes the source.
429
- # - If +source+ responds to instance method +to_io+,
430
- # <tt>source.to_io.read</tt> becomes the source.
431
- # - If +source+ responds to instance method +read+,
432
- # <tt>source.read</tt> becomes the source.
433
- # - If both of the following are true, source becomes the \String <tt>'null'</tt>:
434
- # - Option +allow_blank+ specifies a truthy value.
435
- # - The source, as defined above, is +nil+ or the empty \String <tt>''</tt>.
436
- # - Otherwise, +source+ remains the source.
437
- # - Argument +proc+, if given, must be a \Proc that accepts one argument.
438
- # It will be called recursively with each result (depth-first order).
439
- # See details below.
440
- # BEWARE: This method is meant to serialise data from trusted user input,
441
- # like from your own database server or clients under your control, it could
442
- # be dangerous to allow untrusted users to pass JSON sources into it.
443
- # - Argument +opts+, if given, contains a \Hash of options for the parsing.
444
- # See {Parsing Options}[#module-JSON-label-Parsing+Options].
445
- # The default options can be changed via method JSON.load_default_options=.
446
- #
447
- # ---
448
- #
449
- # When no +proc+ is given, modifies +source+ as above and returns the result of
450
- # <tt>parse(source, opts)</tt>; see #parse.
451
- #
452
- # Source for following examples:
453
- # source = <<-EOT
454
- # {
455
- # "name": "Dave",
456
- # "age" :40,
457
- # "hats": [
458
- # "Cattleman's",
459
- # "Panama",
460
- # "Tophat"
461
- # ]
462
- # }
463
- # EOT
464
- #
465
- # Load a \String:
466
- # ruby = JSON.load(source)
467
- # ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
468
- #
469
- # Load an \IO object:
470
- # require 'stringio'
471
- # object = JSON.load(StringIO.new(source))
472
- # object # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
473
- #
474
- # Load a \File object:
475
- # path = 't.json'
476
- # File.write(path, source)
477
- # File.open(path) do |file|
478
- # JSON.load(file)
479
- # end # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
480
- #
481
- # ---
482
- #
483
- # When +proc+ is given:
484
- # - Modifies +source+ as above.
485
- # - Gets the +result+ from calling <tt>parse(source, opts)</tt>.
486
- # - Recursively calls <tt>proc(result)</tt>.
487
- # - Returns the final result.
488
- #
489
- # Example:
490
- # require 'json'
491
- #
492
- # # Some classes for the example.
493
- # class Base
494
- # def initialize(attributes)
495
- # @attributes = attributes
496
- # end
497
- # end
498
- # class User < Base; end
499
- # class Account < Base; end
500
- # class Admin < Base; end
501
- # # The JSON source.
502
- # json = <<-EOF
503
- # {
504
- # "users": [
505
- # {"type": "User", "username": "jane", "email": "jane@example.com"},
506
- # {"type": "User", "username": "john", "email": "john@example.com"}
507
- # ],
508
- # "accounts": [
509
- # {"account": {"type": "Account", "paid": true, "account_id": "1234"}},
510
- # {"account": {"type": "Account", "paid": false, "account_id": "1235"}}
511
- # ],
512
- # "admins": {"type": "Admin", "password": "0wn3d"}
513
- # }
514
- # EOF
515
- # # Deserializer method.
516
- # def deserialize_obj(obj, safe_types = %w(User Account Admin))
517
- # type = obj.is_a?(Hash) && obj["type"]
518
- # safe_types.include?(type) ? Object.const_get(type).new(obj) : obj
519
- # end
520
- # # Call to JSON.load
521
- # ruby = JSON.load(json, proc {|obj|
522
- # case obj
523
- # when Hash
524
- # obj.each {|k, v| obj[k] = deserialize_obj v }
525
- # when Array
526
- # obj.map! {|v| deserialize_obj v }
527
- # end
528
- # })
529
- # pp ruby
530
- # Output:
531
- # {"users"=>
532
- # [#<User:0x00000000064c4c98
533
- # @attributes=
534
- # {"type"=>"User", "username"=>"jane", "email"=>"jane@example.com"}>,
535
- # #<User:0x00000000064c4bd0
536
- # @attributes=
537
- # {"type"=>"User", "username"=>"john", "email"=>"john@example.com"}>],
538
- # "accounts"=>
539
- # [{"account"=>
540
- # #<Account:0x00000000064c4928
541
- # @attributes={"type"=>"Account", "paid"=>true, "account_id"=>"1234"}>},
542
- # {"account"=>
543
- # #<Account:0x00000000064c4680
544
- # @attributes={"type"=>"Account", "paid"=>false, "account_id"=>"1235"}>}],
545
- # "admins"=>
546
- # #<Admin:0x00000000064c41f8
547
- # @attributes={"type"=>"Admin", "password"=>"0wn3d"}>}
548
- #
549
- def load(source, proc = nil, options = nil)
550
- opts = if options.nil?
551
- load_default_options
552
- else
553
- load_default_options.merge(options)
554
- end
555
-
556
- unless source.is_a?(String)
557
- if source.respond_to? :to_str
558
- source = source.to_str
559
- elsif source.respond_to? :to_io
560
- source = source.to_io.read
561
- elsif source.respond_to?(:read)
562
- source = source.read
563
- end
564
- end
565
-
566
- if opts[:allow_blank] && (source.nil? || source.empty?)
567
- source = 'null'
568
- end
569
- result = parse(source, opts)
570
- recurse_proc(result, &proc) if proc
571
- result
572
- end
573
-
574
- # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
575
- def recurse_proc(result, &proc) # :nodoc:
576
- case result
577
- when Array
578
- result.each { |x| recurse_proc x, &proc }
579
- proc.call result
580
- when Hash
581
- result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
582
- proc.call result
583
- else
584
- proc.call result
585
- end
586
- end
587
-
588
- alias restore load
589
- module_function :restore
590
-
591
- class << self
592
- # Sets or returns the default options for the JSON.dump method.
593
- # Initially:
594
- # opts = JSON.dump_default_options
595
- # opts # => {:max_nesting=>false, :allow_nan=>true}
596
- attr_accessor :dump_default_options
597
- end
598
- self.dump_default_options = {
599
- :max_nesting => false,
600
- :allow_nan => true,
601
- }
602
-
603
- # :call-seq:
604
- # JSON.dump(obj, io = nil, limit = nil)
605
- #
606
- # Dumps +obj+ as a \JSON string, i.e. calls generate on the object and returns the result.
607
- #
608
- # The default options can be changed via method JSON.dump_default_options.
609
- #
610
- # - Argument +io+, if given, should respond to method +write+;
611
- # the \JSON \String is written to +io+, and +io+ is returned.
612
- # If +io+ is not given, the \JSON \String is returned.
613
- # - Argument +limit+, if given, is passed to JSON.generate as option +max_nesting+.
614
- #
615
- # ---
616
- #
617
- # When argument +io+ is not given, returns the \JSON \String generated from +obj+:
618
- # obj = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad}
619
- # json = JSON.dump(obj)
620
- # json # => "{\"foo\":[0,1],\"bar\":{\"baz\":2,\"bat\":3},\"bam\":\"bad\"}"
621
- #
622
- # When argument +io+ is given, writes the \JSON \String to +io+ and returns +io+:
623
- # path = 't.json'
624
- # File.open(path, 'w') do |file|
625
- # JSON.dump(obj, file)
626
- # end # => #<File:t.json (closed)>
627
- # puts File.read(path)
628
- # Output:
629
- # {"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}
630
- def dump(obj, anIO = nil, limit = nil, kwargs = nil)
631
- if kwargs.nil?
632
- if limit.nil?
633
- if anIO.is_a?(Hash)
634
- kwargs = anIO
635
- anIO = nil
636
- end
637
- elsif limit.is_a?(Hash)
638
- kwargs = limit
639
- limit = nil
640
- end
641
- end
642
-
643
- unless anIO.nil?
644
- if anIO.respond_to?(:to_io)
645
- anIO = anIO.to_io
646
- elsif limit.nil? && !anIO.respond_to?(:write)
647
- anIO, limit = nil, anIO
648
- end
649
- end
650
-
651
- opts = JSON.dump_default_options
652
- opts = opts.merge(:max_nesting => limit) if limit
653
- opts = merge_dump_options(opts, **kwargs) if kwargs
654
-
655
- result = begin
656
- generate(obj, opts)
657
- rescue JSON::NestingError
658
- raise ArgumentError, "exceed depth limit"
659
- end
660
-
661
- if anIO.nil?
662
- result
663
- else
664
- anIO.write result
665
- anIO
666
- end
667
- end
668
-
669
- # Encodes string using String.encode.
670
- def self.iconv(to, from, string)
671
- string.encode(to, from)
672
- end
673
-
674
- def merge_dump_options(opts, strict: NOT_SET)
675
- opts = opts.merge(strict: strict) if NOT_SET != strict
676
- opts
677
- end
678
-
679
- class << self
680
- private :merge_dump_options
681
- end
682
- end
683
-
684
- module ::Kernel
685
- private
686
-
687
- # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
688
- # one line.
689
- def j(*objs)
690
- objs.each do |obj|
691
- puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
692
- end
693
- nil
694
- end
695
-
696
- # Outputs _objs_ to STDOUT as JSON strings in a pretty format, with
697
- # indentation and over many lines.
698
- def jj(*objs)
699
- objs.each do |obj|
700
- puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
701
- end
702
- nil
703
- end
704
-
705
- # If _object_ is string-like, parse the string and return the parsed result as
706
- # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
707
- # structure object and return it.
708
- #
709
- # The _opts_ argument is passed through to generate/parse respectively. See
710
- # generate and parse for their documentation.
711
- def JSON(object, *args)
712
- if object.is_a?(String)
713
- return JSON.parse(object, args.first)
714
- elsif object.respond_to?(:to_str)
715
- str = object.to_str
716
- if str.is_a?(String)
717
- return JSON.parse(object.to_str, args.first)
718
- end
719
- end
720
-
721
- JSON.generate(object, args.first)
722
- end
723
- end
724
-
725
- # Extends any Class to include _json_creatable?_ method.
726
- class ::Class
727
- # Returns true if this class can be used to create an instance
728
- # from a serialised JSON string. The class has to implement a class
729
- # method _json_create_ that expects a hash as first parameter. The hash
730
- # should include the required data.
731
- def json_creatable?
732
- respond_to?(:json_create)
733
- end
734
- end