common.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. require 'json/version'
  2. require 'json/generic_object'
  3. module JSON
  4. class << self
  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.
  8. #
  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)
  14. else
  15. JSON.generate(object, opts)
  16. end
  17. end
  18. # Returns the JSON parser class that is used by JSON. This is either
  19. # JSON::Ext::Parser or JSON::Pure::Parser.
  20. attr_reader :parser
  21. # Set the JSON parser class _parser_ to be used by JSON.
  22. def parser=(parser) # :nodoc:
  23. @parser = parser
  24. remove_const :Parser if JSON.const_defined_in?(self, :Parser)
  25. const_set :Parser, parser
  26. end
  27. # Return the constant located at _path_. The format of _path_ has to be
  28. # either ::A::B::C or A::B::C. In any case, A has to be located at the top
  29. # level (absolute namespace path?). If there doesn't exist a constant at
  30. # the given path, an ArgumentError is raised.
  31. def deep_const_get(path) # :nodoc:
  32. path.to_s.split(/::/).inject(Object) do |p, c|
  33. case
  34. when c.empty? then p
  35. when JSON.const_defined_in?(p, c) then p.const_get(c)
  36. else
  37. begin
  38. p.const_missing(c)
  39. rescue NameError => e
  40. raise ArgumentError, "can't get const #{path}: #{e}"
  41. end
  42. end
  43. end
  44. end
  45. # Set the module _generator_ to be used by JSON.
  46. def generator=(generator) # :nodoc:
  47. old, $VERBOSE = $VERBOSE, nil
  48. @generator = generator
  49. generator_methods = generator::GeneratorMethods
  50. for const in generator_methods.constants
  51. klass = deep_const_get(const)
  52. modul = generator_methods.const_get(const)
  53. klass.class_eval do
  54. instance_methods(false).each do |m|
  55. m.to_s == 'to_json' and remove_method m
  56. end
  57. include modul
  58. end
  59. end
  60. self.state = generator::State
  61. const_set :State, self.state
  62. const_set :SAFE_STATE_PROTOTYPE, State.new
  63. const_set :FAST_STATE_PROTOTYPE, State.new(
  64. :indent => '',
  65. :space => '',
  66. :object_nl => "",
  67. :array_nl => "",
  68. :max_nesting => false
  69. )
  70. const_set :PRETTY_STATE_PROTOTYPE, State.new(
  71. :indent => ' ',
  72. :space => ' ',
  73. :object_nl => "\n",
  74. :array_nl => "\n"
  75. )
  76. ensure
  77. $VERBOSE = old
  78. end
  79. # Returns the JSON generator module that is used by JSON. This is
  80. # either JSON::Ext::Generator or JSON::Pure::Generator.
  81. attr_reader :generator
  82. # Returns the JSON generator state class that is used by JSON. This is
  83. # either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
  84. attr_accessor :state
  85. # This is create identifier, which is used to decide if the _json_create_
  86. # hook of a class should be called. It defaults to 'json_class'.
  87. attr_accessor :create_id
  88. end
  89. self.create_id = 'json_class'
  90. NaN = 0.0/0
  91. Infinity = 1.0/0
  92. MinusInfinity = -Infinity
  93. # The base exception for JSON errors.
  94. class JSONError < StandardError
  95. def self.wrap(exception)
  96. obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
  97. obj.set_backtrace exception.backtrace
  98. obj
  99. end
  100. end
  101. # This exception is raised if a parser error occurs.
  102. class ParserError < JSONError; end
  103. # This exception is raised if the nesting of parsed data structures is too
  104. # deep.
  105. class NestingError < ParserError; end
  106. # :stopdoc:
  107. class CircularDatastructure < NestingError; end
  108. # :startdoc:
  109. # This exception is raised if a generator or unparser error occurs.
  110. class GeneratorError < JSONError; end
  111. # For backwards compatibility
  112. UnparserError = GeneratorError
  113. # This exception is raised if the required unicode support is missing on the
  114. # system. Usually this means that the iconv library is not installed.
  115. class MissingUnicodeSupport < JSONError; end
  116. module_function
  117. # Parse the JSON document _source_ into a Ruby data structure and return it.
  118. #
  119. # _opts_ can have the following
  120. # keys:
  121. # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
  122. # structures. Disable depth checking with :max_nesting => false. It defaults
  123. # to 19.
  124. # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
  125. # defiance of RFC 4627 to be parsed by the Parser. This option defaults
  126. # to false.
  127. # * *symbolize_names*: If set to true, returns symbols for the names
  128. # (keys) in a JSON object. Otherwise strings are returned. Strings are
  129. # the default.
  130. # * *create_additions*: If set to false, the Parser doesn't create
  131. # additions even if a matching class and create_id was found. This option
  132. # defaults to true.
  133. # * *object_class*: Defaults to Hash
  134. # * *array_class*: Defaults to Array
  135. def parse(source, opts = {})
  136. Parser.new(source, opts).parse
  137. end
  138. # Parse the JSON document _source_ into a Ruby data structure and return it.
  139. # The bang version of the parse method defaults to the more dangerous values
  140. # for the _opts_ hash, so be sure only to parse trusted _source_ documents.
  141. #
  142. # _opts_ can have the following keys:
  143. # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
  144. # structures. Enable depth checking with :max_nesting => anInteger. The parse!
  145. # methods defaults to not doing max depth checking: This can be dangerous
  146. # if someone wants to fill up your stack.
  147. # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
  148. # defiance of RFC 4627 to be parsed by the Parser. This option defaults
  149. # to true.
  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 true.
  153. def parse!(source, opts = {})
  154. opts = {
  155. :max_nesting => false,
  156. :allow_nan => true
  157. }.update(opts)
  158. Parser.new(source, opts).parse
  159. end
  160. # Generate a JSON document from the Ruby data structure _obj_ and return
  161. # it. _state_ is * a JSON::State object,
  162. # * or a Hash like object (responding to to_hash),
  163. # * an object convertible into a hash by a to_h method,
  164. # that is used as or to configure a State object.
  165. #
  166. # It defaults to a state object, that creates the shortest possible JSON text
  167. # in one line, checks for circular data structures and doesn't allow NaN,
  168. # Infinity, and -Infinity.
  169. #
  170. # A _state_ hash can have the following keys:
  171. # * *indent*: a string used to indent levels (default: ''),
  172. # * *space*: a string that is put after, a : or , delimiter (default: ''),
  173. # * *space_before*: a string that is put before a : pair delimiter (default: ''),
  174. # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
  175. # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
  176. # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
  177. # generated, otherwise an exception is thrown if these values are
  178. # encountered. This options defaults to false.
  179. # * *max_nesting*: The maximum depth of nesting allowed in the data
  180. # structures from which JSON is to be generated. Disable depth checking
  181. # with :max_nesting => false, it defaults to 19.
  182. #
  183. # See also the fast_generate for the fastest creation method with the least
  184. # amount of sanity checks, and the pretty_generate method for some
  185. # defaults for pretty output.
  186. def generate(obj, opts = nil)
  187. if State === opts
  188. state, opts = opts, nil
  189. else
  190. state = SAFE_STATE_PROTOTYPE.dup
  191. end
  192. if opts
  193. if opts.respond_to? :to_hash
  194. opts = opts.to_hash
  195. elsif opts.respond_to? :to_h
  196. opts = opts.to_h
  197. else
  198. raise TypeError, "can't convert #{opts.class} into Hash"
  199. end
  200. state = state.configure(opts)
  201. end
  202. state.generate(obj)
  203. end
  204. # :stopdoc:
  205. # I want to deprecate these later, so I'll first be silent about them, and
  206. # later delete them.
  207. alias unparse generate
  208. module_function :unparse
  209. # :startdoc:
  210. # Generate a JSON document from the Ruby data structure _obj_ and return it.
  211. # This method disables the checks for circles in Ruby objects.
  212. #
  213. # *WARNING*: Be careful not to pass any Ruby data structures with circles as
  214. # _obj_ argument because this will cause JSON to go into an infinite loop.
  215. def fast_generate(obj, opts = nil)
  216. if State === opts
  217. state, opts = opts, nil
  218. else
  219. state = FAST_STATE_PROTOTYPE.dup
  220. end
  221. if opts
  222. if opts.respond_to? :to_hash
  223. opts = opts.to_hash
  224. elsif opts.respond_to? :to_h
  225. opts = opts.to_h
  226. else
  227. raise TypeError, "can't convert #{opts.class} into Hash"
  228. end
  229. state.configure(opts)
  230. end
  231. state.generate(obj)
  232. end
  233. # :stopdoc:
  234. # I want to deprecate these later, so I'll first be silent about them, and later delete them.
  235. alias fast_unparse fast_generate
  236. module_function :fast_unparse
  237. # :startdoc:
  238. # Generate a JSON document from the Ruby data structure _obj_ and return it.
  239. # The returned document is a prettier form of the document returned by
  240. # #unparse.
  241. #
  242. # The _opts_ argument can be used to configure the generator. See the
  243. # generate method for a more detailed explanation.
  244. def pretty_generate(obj, opts = nil)
  245. if State === opts
  246. state, opts = opts, nil
  247. else
  248. state = PRETTY_STATE_PROTOTYPE.dup
  249. end
  250. if opts
  251. if opts.respond_to? :to_hash
  252. opts = opts.to_hash
  253. elsif opts.respond_to? :to_h
  254. opts = opts.to_h
  255. else
  256. raise TypeError, "can't convert #{opts.class} into Hash"
  257. end
  258. state.configure(opts)
  259. end
  260. state.generate(obj)
  261. end
  262. # :stopdoc:
  263. # I want to deprecate these later, so I'll first be silent about them, and later delete them.
  264. alias pretty_unparse pretty_generate
  265. module_function :pretty_unparse
  266. # :startdoc:
  267. class << self
  268. # The global default options for the JSON.load method:
  269. # :max_nesting: false
  270. # :allow_nan: true
  271. # :quirks_mode: true
  272. attr_accessor :load_default_options
  273. end
  274. self.load_default_options = {
  275. :max_nesting => false,
  276. :allow_nan => true,
  277. :quirks_mode => true,
  278. }
  279. # Load a ruby data structure from a JSON _source_ and return it. A source can
  280. # either be a string-like object, an IO-like object, or an object responding
  281. # to the read method. If _proc_ was given, it will be called with any nested
  282. # Ruby object as an argument recursively in depth first order. The default
  283. # options for the parser can be changed via the load_default_options method.
  284. #
  285. # This method is part of the implementation of the load/dump interface of
  286. # Marshal and YAML.
  287. def load(source, proc = nil)
  288. opts = load_default_options
  289. if source.respond_to? :to_str
  290. source = source.to_str
  291. elsif source.respond_to? :to_io
  292. source = source.to_io.read
  293. elsif source.respond_to?(:read)
  294. source = source.read
  295. end
  296. if opts[:quirks_mode] && (source.nil? || source.empty?)
  297. source = 'null'
  298. end
  299. result = parse(source, opts)
  300. recurse_proc(result, &proc) if proc
  301. result
  302. end
  303. # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
  304. def recurse_proc(result, &proc)
  305. case result
  306. when Array
  307. result.each { |x| recurse_proc x, &proc }
  308. proc.call result
  309. when Hash
  310. result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
  311. proc.call result
  312. else
  313. proc.call result
  314. end
  315. end
  316. alias restore load
  317. module_function :restore
  318. class << self
  319. # The global default options for the JSON.dump method:
  320. # :max_nesting: false
  321. # :allow_nan: true
  322. # :quirks_mode: true
  323. attr_accessor :dump_default_options
  324. end
  325. self.dump_default_options = {
  326. :max_nesting => false,
  327. :allow_nan => true,
  328. :quirks_mode => true,
  329. }
  330. # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
  331. # the result.
  332. #
  333. # If anIO (an IO-like object or an object that responds to the write method)
  334. # was given, the resulting JSON is written to it.
  335. #
  336. # If the number of nested arrays or objects exceeds _limit_, an ArgumentError
  337. # exception is raised. This argument is similar (but not exactly the
  338. # same!) to the _limit_ argument in Marshal.dump.
  339. #
  340. # The default options for the generator can be changed via the
  341. # dump_default_options method.
  342. #
  343. # This method is part of the implementation of the load/dump interface of
  344. # Marshal and YAML.
  345. def dump(obj, anIO = nil, limit = nil)
  346. if anIO and limit.nil?
  347. anIO = anIO.to_io if anIO.respond_to?(:to_io)
  348. unless anIO.respond_to?(:write)
  349. limit = anIO
  350. anIO = nil
  351. end
  352. end
  353. opts = JSON.dump_default_options
  354. limit and opts.update(:max_nesting => limit)
  355. result = generate(obj, opts)
  356. if anIO
  357. anIO.write result
  358. anIO
  359. else
  360. result
  361. end
  362. rescue JSON::NestingError
  363. raise ArgumentError, "exceed depth limit"
  364. end
  365. # Swap consecutive bytes of _string_ in place.
  366. def self.swap!(string) # :nodoc:
  367. 0.upto(string.size / 2) do |i|
  368. break unless string[2 * i + 1]
  369. string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
  370. end
  371. string
  372. end
  373. # Shortuct for iconv.
  374. if ::String.method_defined?(:encode) &&
  375. # XXX Rubinius doesn't support ruby 1.9 encoding yet
  376. defined?(RUBY_ENGINE) && RUBY_ENGINE != 'rbx'
  377. then
  378. # Encodes string using Ruby's _String.encode_
  379. def self.iconv(to, from, string)
  380. string.encode(to, from)
  381. end
  382. else
  383. require 'iconv'
  384. # Encodes string using _iconv_ library
  385. def self.iconv(to, from, string)
  386. Iconv.conv(to, from, string)
  387. end
  388. end
  389. if ::Object.method(:const_defined?).arity == 1
  390. def self.const_defined_in?(modul, constant)
  391. modul.const_defined?(constant)
  392. end
  393. else
  394. def self.const_defined_in?(modul, constant)
  395. modul.const_defined?(constant, false)
  396. end
  397. end
  398. end
  399. module ::Kernel
  400. private
  401. # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
  402. # one line.
  403. def j(*objs)
  404. objs.each do |obj|
  405. puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
  406. end
  407. nil
  408. end
  409. # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
  410. # indentation and over many lines.
  411. def jj(*objs)
  412. objs.each do |obj|
  413. puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
  414. end
  415. nil
  416. end
  417. # If _object_ is string-like, parse the string and return the parsed result as
  418. # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
  419. # structure object and return it.
  420. #
  421. # The _opts_ argument is passed through to generate/parse respectively. See
  422. # generate and parse for their documentation.
  423. def JSON(object, *args)
  424. if object.respond_to? :to_str
  425. JSON.parse(object.to_str, args.first)
  426. else
  427. JSON.generate(object, args.first)
  428. end
  429. end
  430. end
  431. # Extends any Class to include _json_creatable?_ method.
  432. class ::Class
  433. # Returns true if this class can be used to create an instance
  434. # from a serialised JSON string. The class has to implement a class
  435. # method _json_create_ that expects a hash as first parameter. The hash
  436. # should include the required data.
  437. def json_creatable?
  438. respond_to?(:json_create)
  439. end
  440. end