5 # If _object_ is string-like, parse the string and return the parsed result
6 # as a Ruby data structure. Otherwise generate a JSON text from the Ruby
7 # data structure object and return it.
9 # The _opts_ argument is passed through to generate/parse respectively. See
10 # generate and parse for their documentation.
11 def [](object, opts = {})
12 if object.respond_to? :to_str
13 JSON.parse(object.to_str, opts)
15 JSON.generate(object, opts)
19 # Returns the JSON parser class that is used by JSON. This is either
20 # JSON::Ext::Parser or JSON::Pure::Parser.
23 # Set the JSON parser class _parser_ to be used by JSON.
24 def parser=(parser) # :nodoc:
26 remove_const :Parser if JSON.const_defined_in?(self, :Parser)
27 const_set :Parser, parser
30 # Return the constant located at _path_. The format of _path_ has to be
31 # either ::A::B::C or A::B::C. In any case, A has to be located at the top
32 # level (absolute namespace path?). If there doesn't exist a constant at
33 # the given path, an ArgumentError is raised.
34 def deep_const_get(path) # :nodoc:
35 path.to_s.split(/::/).inject(Object) do |p, c|
38 when JSON.const_defined_in?(p, c) then p.const_get(c)
43 raise ArgumentError, "can't get const #{path}: #{e}"
49 # Set the module _generator_ to be used by JSON.
50 def generator=(generator) # :nodoc:
51 old, $VERBOSE = $VERBOSE, nil
52 @generator = generator
53 generator_methods = generator::GeneratorMethods
54 for const in generator_methods.constants
55 klass = deep_const_get(const)
56 modul = generator_methods.const_get(const)
58 instance_methods(false).each do |m|
59 m.to_s == 'to_json' and remove_method m
64 self.state = generator::State
65 const_set :State, self.state
66 const_set :SAFE_STATE_PROTOTYPE, State.new
67 const_set :FAST_STATE_PROTOTYPE, State.new(
74 const_set :PRETTY_STATE_PROTOTYPE, State.new(
84 # Returns the JSON generator module that is used by JSON. This is
85 # either JSON::Ext::Generator or JSON::Pure::Generator.
86 attr_reader :generator
88 # Returns the JSON generator state class that is used by JSON. This is
89 # either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
92 # This is create identifier, which is used to decide if the _json_create_
93 # hook of a class should be called. It defaults to 'json_class'.
94 attr_accessor :create_id
96 self.create_id = 'json_class'
102 MinusInfinity = -Infinity
104 # The base exception for JSON errors.
105 class JSONError < StandardError; end
107 # This exception is raised if a parser error occurs.
108 class ParserError < JSONError; end
110 # This exception is raised if the nesting of parsed data structures is too
112 class NestingError < ParserError; end
115 class CircularDatastructure < NestingError; end
118 # This exception is raised if a generator or unparser error occurs.
119 class GeneratorError < JSONError; end
120 # For backwards compatibility
121 UnparserError = GeneratorError
123 # This exception is raised if the required unicode support is missing on the
124 # system. Usually this means that the iconv library is not installed.
125 class MissingUnicodeSupport < JSONError; end
129 # Parse the JSON document _source_ into a Ruby data structure and return it.
131 # _opts_ can have the following
133 # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
134 # structures. Disable depth checking with :max_nesting => false. It defaults
136 # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
137 # defiance of RFC 4627 to be parsed by the Parser. This option defaults
139 # * *symbolize_names*: If set to true, returns symbols for the names
140 # (keys) in a JSON object. Otherwise strings are returned. Strings are
142 # * *create_additions*: If set to false, the Parser doesn't create
143 # additions even if a matching class and create_id was found. This option
145 # * *object_class*: Defaults to Hash
146 # * *array_class*: Defaults to Array
147 def parse(source, opts = {})
148 Parser.new(source, opts).parse
151 # Parse the JSON document _source_ into a Ruby data structure and return it.
152 # The bang version of the parse method defaults to the more dangerous values
153 # for the _opts_ hash, so be sure only to parse trusted _source_ documents.
155 # _opts_ can have the following keys:
156 # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
157 # structures. Enable depth checking with :max_nesting => anInteger. The parse!
158 # methods defaults to not doing max depth checking: This can be dangerous
159 # if someone wants to fill up your stack.
160 # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
161 # defiance of RFC 4627 to be parsed by the Parser. This option defaults
163 # * *create_additions*: If set to false, the Parser doesn't create
164 # additions even if a matching class and create_id was found. This option
166 def parse!(source, opts = {})
168 :max_nesting => false,
171 Parser.new(source, opts).parse
174 # Generate a JSON document from the Ruby data structure _obj_ and return
175 # it. _state_ is * a JSON::State object,
176 # * or a Hash like object (responding to to_hash),
177 # * an object convertible into a hash by a to_h method,
178 # that is used as or to configure a State object.
180 # It defaults to a state object, that creates the shortest possible JSON text
181 # in one line, checks for circular data structures and doesn't allow NaN,
182 # Infinity, and -Infinity.
184 # A _state_ hash can have the following keys:
185 # * *indent*: a string used to indent levels (default: ''),
186 # * *space*: a string that is put after, a : or , delimiter (default: ''),
187 # * *space_before*: a string that is put before a : pair delimiter (default: ''),
188 # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
189 # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
190 # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
191 # generated, otherwise an exception is thrown if these values are
192 # encountered. This options defaults to false.
193 # * *max_nesting*: The maximum depth of nesting allowed in the data
194 # structures from which JSON is to be generated. Disable depth checking
195 # with :max_nesting => false, it defaults to 19.
197 # See also the fast_generate for the fastest creation method with the least
198 # amount of sanity checks, and the pretty_generate method for some
199 # defaults for pretty output.
200 def generate(obj, opts = nil)
202 state, opts = opts, nil
204 state = SAFE_STATE_PROTOTYPE.dup
207 if opts.respond_to? :to_hash
209 elsif opts.respond_to? :to_h
212 raise TypeError, "can't convert #{opts.class} into Hash"
214 state = state.configure(opts)
220 # I want to deprecate these later, so I'll first be silent about them, and
222 alias unparse generate
223 module_function :unparse
226 # Generate a JSON document from the Ruby data structure _obj_ and return it.
227 # This method disables the checks for circles in Ruby objects.
229 # *WARNING*: Be careful not to pass any Ruby data structures with circles as
230 # _obj_ argument because this will cause JSON to go into an infinite loop.
231 def fast_generate(obj, opts = nil)
233 state, opts = opts, nil
235 state = FAST_STATE_PROTOTYPE.dup
238 if opts.respond_to? :to_hash
240 elsif opts.respond_to? :to_h
243 raise TypeError, "can't convert #{opts.class} into Hash"
245 state.configure(opts)
251 # I want to deprecate these later, so I'll first be silent about them, and later delete them.
252 alias fast_unparse fast_generate
253 module_function :fast_unparse
256 # Generate a JSON document from the Ruby data structure _obj_ and return it.
257 # The returned document is a prettier form of the document returned by
260 # The _opts_ argument can be used to configure the generator. See the
261 # generate method for a more detailed explanation.
262 def pretty_generate(obj, opts = nil)
264 state, opts = opts, nil
266 state = PRETTY_STATE_PROTOTYPE.dup
269 if opts.respond_to? :to_hash
271 elsif opts.respond_to? :to_h
274 raise TypeError, "can't convert #{opts.class} into Hash"
276 state.configure(opts)
282 # I want to deprecate these later, so I'll first be silent about them, and later delete them.
283 alias pretty_unparse pretty_generate
284 module_function :pretty_unparse
287 # Load a ruby data structure from a JSON _source_ and return it. A source can
288 # either be a string-like object, an IO-like object, or an object responding
289 # to the read method. If _proc_ was given, it will be called with any nested
290 # Ruby object as an argument recursively in depth first order. To modify the
291 # default options pass in the optional _options_ argument as well.
293 # This method is part of the implementation of the load/dump interface of
295 def load(source, proc = nil, options = {})
296 load_default_options = {
297 :max_nesting => false,
299 :create_additions => false
301 opts = load_default_options.merge options
302 if source.respond_to? :to_str
303 source = source.to_str
304 elsif source.respond_to? :to_io
305 source = source.to_io.read
309 result = parse(source, opts)
310 recurse_proc(result, &proc) if proc
314 # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
315 def recurse_proc(result, &proc)
318 result.each { |x| recurse_proc x, &proc }
321 result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
329 module_function :restore
331 # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
334 # If anIO (an IO-like object or an object that responds to the write method)
335 # was given, the resulting JSON is written to it.
337 # If the number of nested arrays or objects exceeds _limit_, an ArgumentError
338 # exception is raised. This argument is similar (but not exactly the
339 # same!) to the _limit_ argument in Marshal.dump.
341 # This method is part of the implementation of the load/dump interface of
343 def dump(obj, anIO = nil, limit = nil)
344 if anIO and limit.nil?
345 anIO = anIO.to_io if anIO.respond_to?(:to_io)
346 unless anIO.respond_to?(:write)
352 result = generate(obj, :allow_nan => true, :max_nesting => limit)
359 rescue JSON::NestingError
360 raise ArgumentError, "exceed depth limit"
363 # Swap consecutive bytes of _string_ in place.
364 def self.swap!(string) # :nodoc:
365 0.upto(string.size / 2) do |i|
366 break unless string[2 * i + 1]
367 string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
372 # Shortuct for iconv.
373 if ::String.method_defined?(:encode)
374 # Encodes string using Ruby's _String.encode_
375 def self.iconv(to, from, string)
376 string.encode(to, from)
380 # Encodes string using _iconv_ library
381 def self.iconv(to, from, string)
382 Iconv.conv(to, from, string)
386 if ::Object.method(:const_defined?).arity == 1
387 def self.const_defined_in?(modul, constant)
388 modul.const_defined?(constant)
391 def self.const_defined_in?(modul, constant)
392 modul.const_defined?(constant, false)
400 # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
404 puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
409 # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
410 # indentation and over many lines.
413 puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
418 # If _object_ is string-like, parse the string and return the parsed result as
419 # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
420 # structure object and return it.
422 # The _opts_ argument is passed through to generate/parse respectively. See
423 # generate and parse for their documentation.
424 def JSON(object, *args)
425 if object.respond_to? :to_str
426 JSON.parse(object.to_str, args.first)
428 JSON.generate(object, args.first)
433 # Extends any Class to include _json_creatable?_ method.
435 # Returns true if this class can be used to create an instance
436 # from a serialised JSON string. The class has to implement a class
437 # method _json_create_ that expects a hash as first parameter. The hash
438 # should include the required data.
440 respond_to?(:json_create)