json-jruby 1.1.2-universal-java-1.5
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.rb +235 -0
- data/lib/json/add/core.rb +127 -0
- data/lib/json/add/rails.rb +58 -0
- data/lib/json/common.rb +354 -0
- data/lib/json/ext.rb +13 -0
- data/lib/json/ext/generator.jar +0 -0
- data/lib/json/ext/parser.jar +0 -0
- data/lib/json/pure.rb +75 -0
- data/lib/json/pure/generator.rb +394 -0
- data/lib/json/pure/parser.rb +259 -0
- data/lib/json/version.rb +9 -0
- data/tests/fixtures/fail1.json +1 -0
- data/tests/fixtures/fail10.json +1 -0
- data/tests/fixtures/fail11.json +1 -0
- data/tests/fixtures/fail12.json +1 -0
- data/tests/fixtures/fail13.json +1 -0
- data/tests/fixtures/fail14.json +1 -0
- data/tests/fixtures/fail18.json +1 -0
- data/tests/fixtures/fail19.json +1 -0
- data/tests/fixtures/fail2.json +1 -0
- data/tests/fixtures/fail20.json +1 -0
- data/tests/fixtures/fail21.json +1 -0
- data/tests/fixtures/fail22.json +1 -0
- data/tests/fixtures/fail23.json +1 -0
- data/tests/fixtures/fail24.json +1 -0
- data/tests/fixtures/fail25.json +1 -0
- data/tests/fixtures/fail27.json +2 -0
- data/tests/fixtures/fail28.json +2 -0
- data/tests/fixtures/fail3.json +1 -0
- data/tests/fixtures/fail4.json +1 -0
- data/tests/fixtures/fail5.json +1 -0
- data/tests/fixtures/fail6.json +1 -0
- data/tests/fixtures/fail7.json +1 -0
- data/tests/fixtures/fail8.json +1 -0
- data/tests/fixtures/fail9.json +1 -0
- data/tests/fixtures/pass1.json +56 -0
- data/tests/fixtures/pass15.json +1 -0
- data/tests/fixtures/pass16.json +1 -0
- data/tests/fixtures/pass17.json +1 -0
- data/tests/fixtures/pass2.json +1 -0
- data/tests/fixtures/pass26.json +1 -0
- data/tests/fixtures/pass3.json +6 -0
- data/tests/runner.rb +26 -0
- data/tests/test_json.rb +294 -0
- data/tests/test_json_addition.rb +144 -0
- data/tests/test_json_fixtures.rb +30 -0
- data/tests/test_json_generate.rb +100 -0
- data/tests/test_json_rails.rb +114 -0
- data/tests/test_json_unicode.rb +61 -0
- metadata +99 -0
data/lib/json.rb
ADDED
@@ -0,0 +1,235 @@
|
|
1
|
+
require 'json/common'
|
2
|
+
# = json - JSON for Ruby
|
3
|
+
#
|
4
|
+
# == Description
|
5
|
+
#
|
6
|
+
# This is a implementation of the JSON specification according to RFC 4627
|
7
|
+
# (http://www.ietf.org/rfc/rfc4627.txt). Starting from version 1.0.0 on there
|
8
|
+
# will be two variants available:
|
9
|
+
#
|
10
|
+
# * A pure ruby variant, that relies on the iconv and the stringscan
|
11
|
+
# extensions, which are both part of the ruby standard library.
|
12
|
+
# * The quite a bit faster C extension variant, which is in parts implemented
|
13
|
+
# in C and comes with its own unicode conversion functions and a parser
|
14
|
+
# generated by the ragel state machine compiler
|
15
|
+
# (http://www.cs.queensu.ca/~thurston/ragel).
|
16
|
+
#
|
17
|
+
# Both variants of the JSON generator escape all non-ASCII an control
|
18
|
+
# characters with \uXXXX escape sequences, and support UTF-16 surrogate pairs
|
19
|
+
# in order to be able to generate the whole range of unicode code points. This
|
20
|
+
# means that generated JSON text is encoded as UTF-8 (because ASCII is a subset
|
21
|
+
# of UTF-8) and at the same time avoids decoding problems for receiving
|
22
|
+
# endpoints, that don't expect UTF-8 encoded texts. On the negative side this
|
23
|
+
# may lead to a bit longer strings than necessarry.
|
24
|
+
#
|
25
|
+
# All strings, that are to be encoded as JSON strings, should be UTF-8 byte
|
26
|
+
# sequences on the Ruby side. To encode raw binary strings, that aren't UTF-8
|
27
|
+
# encoded, please use the to_json_raw_object method of String (which produces
|
28
|
+
# an object, that contains a byte array) and decode the result on the receiving
|
29
|
+
# endpoint.
|
30
|
+
#
|
31
|
+
# == Author
|
32
|
+
#
|
33
|
+
# Florian Frank <mailto:flori@ping.de>
|
34
|
+
#
|
35
|
+
# == License
|
36
|
+
#
|
37
|
+
# This software is distributed under the same license as Ruby itself, see
|
38
|
+
# http://www.ruby-lang.org/en/LICENSE.txt.
|
39
|
+
#
|
40
|
+
# == Download
|
41
|
+
#
|
42
|
+
# The latest version of this library can be downloaded at
|
43
|
+
#
|
44
|
+
# * http://rubyforge.org/frs?group_id=953
|
45
|
+
#
|
46
|
+
# Online Documentation should be located at
|
47
|
+
#
|
48
|
+
# * http://json.rubyforge.org
|
49
|
+
#
|
50
|
+
# == Usage
|
51
|
+
#
|
52
|
+
# To use JSON you can
|
53
|
+
# require 'json'
|
54
|
+
# to load the installed variant (either the extension 'json' or the pure
|
55
|
+
# variant 'json_pure'). If you have installed the extension variant, you can
|
56
|
+
# pick either the extension variant or the pure variant by typing
|
57
|
+
# require 'json/ext'
|
58
|
+
# or
|
59
|
+
# require 'json/pure'
|
60
|
+
#
|
61
|
+
# You can choose to load a set of common additions to ruby core's objects if
|
62
|
+
# you
|
63
|
+
# require 'json/add/core'
|
64
|
+
#
|
65
|
+
# After requiring this you can, e. g., serialise/deserialise Ruby ranges:
|
66
|
+
#
|
67
|
+
# JSON JSON(1..10) # => 1..10
|
68
|
+
#
|
69
|
+
# To find out how to add JSON support to other or your own classes, read the
|
70
|
+
# Examples section below.
|
71
|
+
#
|
72
|
+
# To get the best compatibility to rails' JSON implementation, you can
|
73
|
+
# require 'json/add/rails'
|
74
|
+
#
|
75
|
+
# Both of the additions attempt to require 'json' (like above) first, if it has
|
76
|
+
# not been required yet.
|
77
|
+
#
|
78
|
+
# == Speed Comparisons
|
79
|
+
#
|
80
|
+
# I have created some benchmark results (see the benchmarks subdir of the
|
81
|
+
# package) for the JSON-Parser to estimate the speed up in the C extension:
|
82
|
+
#
|
83
|
+
# JSON::Pure::Parser:: 28.90 calls/second
|
84
|
+
# JSON::Ext::Parser:: 505.50 calls/second
|
85
|
+
#
|
86
|
+
# This is ca. <b>17.5</b> times the speed of the pure Ruby implementation.
|
87
|
+
#
|
88
|
+
# I have benchmarked the JSON-Generator as well. This generates a few more
|
89
|
+
# values, because there are different modes, that also influence the achieved
|
90
|
+
# speed:
|
91
|
+
#
|
92
|
+
# * JSON::Pure::Generator:
|
93
|
+
# generate:: 35.06 calls/second
|
94
|
+
# pretty_generate:: 34.00 calls/second
|
95
|
+
# fast_generate:: 41.06 calls/second
|
96
|
+
#
|
97
|
+
# * JSON::Ext::Generator:
|
98
|
+
# generate:: 492.11 calls/second
|
99
|
+
# pretty_generate:: 348.85 calls/second
|
100
|
+
# fast_generate:: 541.60 calls/second
|
101
|
+
#
|
102
|
+
# * Speedup Ext/Pure:
|
103
|
+
# generate safe:: 14.0 times
|
104
|
+
# generate pretty:: 10.3 times
|
105
|
+
# generate fast:: 13.2 times
|
106
|
+
#
|
107
|
+
# The rails framework includes a generator as well, also it seems to be rather
|
108
|
+
# slow: I measured only 23.87 calls/second which is slower than any of my pure
|
109
|
+
# generator results. Here a comparison of the different speedups with the Rails
|
110
|
+
# measurement as the divisor:
|
111
|
+
#
|
112
|
+
# * Speedup Pure/Rails:
|
113
|
+
# generate safe:: 1.5 times
|
114
|
+
# generate pretty:: 1.4 times
|
115
|
+
# generate fast:: 1.7 times
|
116
|
+
#
|
117
|
+
# * Speedup Ext/Rails:
|
118
|
+
# generate safe:: 20.6 times
|
119
|
+
# generate pretty:: 14.6 times
|
120
|
+
# generate fast:: 22.7 times
|
121
|
+
#
|
122
|
+
# To achieve the fastest JSON text output, you can use the
|
123
|
+
# fast_generate/fast_unparse methods. Beware, that this will disable the
|
124
|
+
# checking for circular Ruby data structures, which may cause JSON to go into
|
125
|
+
# an infinite loop.
|
126
|
+
#
|
127
|
+
# == Examples
|
128
|
+
#
|
129
|
+
# To create a JSON text from a ruby data structure, you
|
130
|
+
# can call JSON.generate (or JSON.unparse) like that:
|
131
|
+
#
|
132
|
+
# json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
|
133
|
+
# # => "[1,2,{\"a\":3.141},false,true,null,\"4..10\"]"
|
134
|
+
#
|
135
|
+
# To create a valid JSON text you have to make sure, that the output is
|
136
|
+
# embedded in either a JSON array [] or a JSON object {}. The easiest way to do
|
137
|
+
# this, is by putting your values in a Ruby Array or Hash instance.
|
138
|
+
#
|
139
|
+
# To get back a ruby data structure from a JSON text, you have to call
|
140
|
+
# JSON.parse on it:
|
141
|
+
#
|
142
|
+
# JSON.parse json
|
143
|
+
# # => [1, 2, {"a"=>3.141}, false, true, nil, "4..10"]
|
144
|
+
#
|
145
|
+
# Note, that the range from the original data structure is a simple
|
146
|
+
# string now. The reason for this is, that JSON doesn't support ranges
|
147
|
+
# or arbitrary classes. In this case the json library falls back to call
|
148
|
+
# Object#to_json, which is the same as #to_s.to_json.
|
149
|
+
#
|
150
|
+
# It's possible to add JSON support serialization to arbitrary classes by
|
151
|
+
# simply implementing a more specialized version of the #to_json method, that
|
152
|
+
# should return a JSON object (a hash converted to JSON with #to_json) like
|
153
|
+
# this (don't forget the *a for all the arguments):
|
154
|
+
#
|
155
|
+
# class Range
|
156
|
+
# def to_json(*a)
|
157
|
+
# {
|
158
|
+
# 'json_class' => self.class.name, # = 'Range'
|
159
|
+
# 'data' => [ first, last, exclude_end? ]
|
160
|
+
# }.to_json(*a)
|
161
|
+
# end
|
162
|
+
# end
|
163
|
+
#
|
164
|
+
# The hash key 'json_class' is the class, that will be asked to deserialise the
|
165
|
+
# JSON representation later. In this case it's 'Range', but any namespace of
|
166
|
+
# the form 'A::B' or '::A::B' will do. All other keys are arbitrary and can be
|
167
|
+
# used to store the necessary data to configure the object to be deserialised.
|
168
|
+
#
|
169
|
+
# If a the key 'json_class' is found in a JSON object, the JSON parser checks
|
170
|
+
# if the given class responds to the json_create class method. If so, it is
|
171
|
+
# called with the JSON object converted to a Ruby hash. So a range can
|
172
|
+
# be deserialised by implementing Range.json_create like this:
|
173
|
+
#
|
174
|
+
# class Range
|
175
|
+
# def self.json_create(o)
|
176
|
+
# new(*o['data'])
|
177
|
+
# end
|
178
|
+
# end
|
179
|
+
#
|
180
|
+
# Now it possible to serialise/deserialise ranges as well:
|
181
|
+
#
|
182
|
+
# json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
|
183
|
+
# # => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]"
|
184
|
+
# JSON.parse json
|
185
|
+
# # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
|
186
|
+
#
|
187
|
+
# JSON.generate always creates the shortest possible string representation of a
|
188
|
+
# ruby data structure in one line. This good for data storage or network
|
189
|
+
# protocols, but not so good for humans to read. Fortunately there's also
|
190
|
+
# JSON.pretty_generate (or JSON.pretty_generate) that creates a more
|
191
|
+
# readable output:
|
192
|
+
#
|
193
|
+
# puts JSON.pretty_generate([1, 2, {"a"=>3.141}, false, true, nil, 4..10])
|
194
|
+
# [
|
195
|
+
# 1,
|
196
|
+
# 2,
|
197
|
+
# {
|
198
|
+
# "a": 3.141
|
199
|
+
# },
|
200
|
+
# false,
|
201
|
+
# true,
|
202
|
+
# null,
|
203
|
+
# {
|
204
|
+
# "json_class": "Range",
|
205
|
+
# "data": [
|
206
|
+
# 4,
|
207
|
+
# 10,
|
208
|
+
# false
|
209
|
+
# ]
|
210
|
+
# }
|
211
|
+
# ]
|
212
|
+
#
|
213
|
+
# There are also the methods Kernel#j for unparse, and Kernel#jj for
|
214
|
+
# pretty_unparse output to the console, that work analogous to Core Ruby's p
|
215
|
+
# and the pp library's pp methods.
|
216
|
+
#
|
217
|
+
# The script tools/server.rb contains a small example if you want to test, how
|
218
|
+
# receiving a JSON object from a webrick server in your browser with the
|
219
|
+
# javasript prototype library (http://www.prototypejs.org) works.
|
220
|
+
#
|
221
|
+
module JSON
|
222
|
+
require 'json/version'
|
223
|
+
|
224
|
+
if VARIANT_BINARY
|
225
|
+
require 'json/ext'
|
226
|
+
else
|
227
|
+
begin
|
228
|
+
require 'json/ext'
|
229
|
+
rescue LoadError
|
230
|
+
require 'json/pure'
|
231
|
+
end
|
232
|
+
end
|
233
|
+
|
234
|
+
JSON_LOADED = true
|
235
|
+
end
|
@@ -0,0 +1,127 @@
|
|
1
|
+
# This file contains implementations of ruby core's custom objects for
|
2
|
+
# serialisation/deserialisation.
|
3
|
+
|
4
|
+
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
|
5
|
+
::JSON::JSON_LOADED
|
6
|
+
require 'json'
|
7
|
+
end
|
8
|
+
require 'date'
|
9
|
+
|
10
|
+
class Time
|
11
|
+
def self.json_create(object)
|
12
|
+
if usec = object.delete('u') # used to be tv_usec -> tv_nsec
|
13
|
+
object['n'] = usec * 1000
|
14
|
+
end
|
15
|
+
if respond_to?(:tv_nsec)
|
16
|
+
at(*object.values_at('s', 'n'))
|
17
|
+
else
|
18
|
+
at(object['s'], object['n'] / 1000)
|
19
|
+
end
|
20
|
+
end
|
21
|
+
|
22
|
+
def to_json(*args)
|
23
|
+
{
|
24
|
+
'json_class' => self.class.name,
|
25
|
+
's' => tv_sec,
|
26
|
+
'n' => respond_to?(:tv_nsec) ? tv_nsec : tv_usec * 1000
|
27
|
+
}.to_json(*args)
|
28
|
+
end
|
29
|
+
end
|
30
|
+
|
31
|
+
class Date
|
32
|
+
def self.json_create(object)
|
33
|
+
civil(*object.values_at('y', 'm', 'd', 'sg'))
|
34
|
+
end
|
35
|
+
|
36
|
+
def to_json(*args)
|
37
|
+
{
|
38
|
+
'json_class' => self.class.name,
|
39
|
+
'y' => year,
|
40
|
+
'm' => month,
|
41
|
+
'd' => day,
|
42
|
+
'sg' => sg,
|
43
|
+
}.to_json(*args)
|
44
|
+
end
|
45
|
+
end
|
46
|
+
|
47
|
+
class DateTime
|
48
|
+
def self.json_create(object)
|
49
|
+
args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
|
50
|
+
of_a, of_b = object['of'].split('/')
|
51
|
+
args << Rational(of_a.to_i, of_b.to_i)
|
52
|
+
args << object['sg']
|
53
|
+
civil(*args)
|
54
|
+
end
|
55
|
+
|
56
|
+
def to_json(*args)
|
57
|
+
{
|
58
|
+
'json_class' => self.class.name,
|
59
|
+
'y' => year,
|
60
|
+
'm' => month,
|
61
|
+
'd' => day,
|
62
|
+
'H' => hour,
|
63
|
+
'M' => min,
|
64
|
+
'S' => sec,
|
65
|
+
'of' => offset.to_s,
|
66
|
+
'sg' => sg,
|
67
|
+
}.to_json(*args)
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
class Range
|
72
|
+
def self.json_create(object)
|
73
|
+
new(*object['a'])
|
74
|
+
end
|
75
|
+
|
76
|
+
def to_json(*args)
|
77
|
+
{
|
78
|
+
'json_class' => self.class.name,
|
79
|
+
'a' => [ first, last, exclude_end? ]
|
80
|
+
}.to_json(*args)
|
81
|
+
end
|
82
|
+
end
|
83
|
+
|
84
|
+
class Struct
|
85
|
+
def self.json_create(object)
|
86
|
+
new(*object['v'])
|
87
|
+
end
|
88
|
+
|
89
|
+
def to_json(*args)
|
90
|
+
klass = self.class.name
|
91
|
+
klass.empty? and raise JSON::JSONError, "Only named structs are supported!"
|
92
|
+
{
|
93
|
+
'json_class' => klass,
|
94
|
+
'v' => values,
|
95
|
+
}.to_json(*args)
|
96
|
+
end
|
97
|
+
end
|
98
|
+
|
99
|
+
class Exception
|
100
|
+
def self.json_create(object)
|
101
|
+
result = new(object['m'])
|
102
|
+
result.set_backtrace object['b']
|
103
|
+
result
|
104
|
+
end
|
105
|
+
|
106
|
+
def to_json(*args)
|
107
|
+
{
|
108
|
+
'json_class' => self.class.name,
|
109
|
+
'm' => message,
|
110
|
+
'b' => backtrace,
|
111
|
+
}.to_json(*args)
|
112
|
+
end
|
113
|
+
end
|
114
|
+
|
115
|
+
class Regexp
|
116
|
+
def self.json_create(object)
|
117
|
+
new(object['s'], object['o'])
|
118
|
+
end
|
119
|
+
|
120
|
+
def to_json(*)
|
121
|
+
{
|
122
|
+
'json_class' => self.class.name,
|
123
|
+
'o' => options,
|
124
|
+
's' => source,
|
125
|
+
}.to_json
|
126
|
+
end
|
127
|
+
end
|
@@ -0,0 +1,58 @@
|
|
1
|
+
# This file contains implementations of rails custom objects for
|
2
|
+
# serialisation/deserialisation.
|
3
|
+
|
4
|
+
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
|
5
|
+
::JSON::JSON_LOADED
|
6
|
+
require 'json'
|
7
|
+
end
|
8
|
+
|
9
|
+
class Object
|
10
|
+
def self.json_create(object)
|
11
|
+
obj = new
|
12
|
+
for key, value in object
|
13
|
+
next if key == 'json_class'
|
14
|
+
instance_variable_set "@#{key}", value
|
15
|
+
end
|
16
|
+
obj
|
17
|
+
end
|
18
|
+
|
19
|
+
def to_json(*a)
|
20
|
+
result = {
|
21
|
+
'json_class' => self.class.name
|
22
|
+
}
|
23
|
+
instance_variables.inject(result) do |r, name|
|
24
|
+
r[name[1..-1]] = instance_variable_get name
|
25
|
+
r
|
26
|
+
end
|
27
|
+
result.to_json(*a)
|
28
|
+
end
|
29
|
+
end
|
30
|
+
|
31
|
+
class Symbol
|
32
|
+
def to_json(*a)
|
33
|
+
to_s.to_json(*a)
|
34
|
+
end
|
35
|
+
end
|
36
|
+
|
37
|
+
module Enumerable
|
38
|
+
def to_json(*a)
|
39
|
+
to_a.to_json(*a)
|
40
|
+
end
|
41
|
+
end
|
42
|
+
|
43
|
+
# class Regexp
|
44
|
+
# def to_json(*)
|
45
|
+
# inspect
|
46
|
+
# end
|
47
|
+
# end
|
48
|
+
#
|
49
|
+
# The above rails definition has some problems:
|
50
|
+
#
|
51
|
+
# 1. { 'foo' => /bar/ }.to_json # => "{foo: /bar/}"
|
52
|
+
# This isn't valid JSON, because the regular expression syntax is not
|
53
|
+
# defined in RFC 4627. (And unquoted strings are disallowed there, too.)
|
54
|
+
# Though it is valid Javascript.
|
55
|
+
#
|
56
|
+
# 2. { 'foo' => /bar/mix }.to_json # => "{foo: /bar/mix}"
|
57
|
+
# This isn't even valid Javascript.
|
58
|
+
|
data/lib/json/common.rb
ADDED
@@ -0,0 +1,354 @@
|
|
1
|
+
require 'json/version'
|
2
|
+
|
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
|
+
|
19
|
+
# Returns the JSON parser class, that is used by JSON. This might be either
|
20
|
+
# JSON::Ext::Parser or JSON::Pure::Parser.
|
21
|
+
attr_reader :parser
|
22
|
+
|
23
|
+
# Set the JSON parser class _parser_ to be used by JSON.
|
24
|
+
def parser=(parser) # :nodoc:
|
25
|
+
@parser = parser
|
26
|
+
remove_const :Parser if const_defined? :Parser
|
27
|
+
const_set :Parser, parser
|
28
|
+
end
|
29
|
+
|
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 = path.to_s
|
36
|
+
path.split(/::/).inject(Object) do |p, c|
|
37
|
+
case
|
38
|
+
when c.empty? then p
|
39
|
+
when p.const_defined?(c) then p.const_get(c)
|
40
|
+
else raise ArgumentError, "can't find const #{path}"
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
44
|
+
|
45
|
+
# Set the module _generator_ to be used by JSON.
|
46
|
+
def generator=(generator) # :nodoc:
|
47
|
+
@generator = generator
|
48
|
+
generator_methods = generator::GeneratorMethods
|
49
|
+
for const in generator_methods.constants
|
50
|
+
klass = deep_const_get(const)
|
51
|
+
modul = generator_methods.const_get(const)
|
52
|
+
klass.class_eval do
|
53
|
+
instance_methods(false).each do |m|
|
54
|
+
m.to_s == 'to_json' and remove_method m
|
55
|
+
end
|
56
|
+
include modul
|
57
|
+
end
|
58
|
+
end
|
59
|
+
self.state = generator::State
|
60
|
+
const_set :State, self.state
|
61
|
+
end
|
62
|
+
|
63
|
+
# Returns the JSON generator modul, that is used by JSON. This might be
|
64
|
+
# either JSON::Ext::Generator or JSON::Pure::Generator.
|
65
|
+
attr_reader :generator
|
66
|
+
|
67
|
+
# Returns the JSON generator state class, that is used by JSON. This might
|
68
|
+
# be either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
|
69
|
+
attr_accessor :state
|
70
|
+
|
71
|
+
# This is create identifier, that is used to decide, if the _json_create_
|
72
|
+
# hook of a class should be called. It defaults to 'json_class'.
|
73
|
+
attr_accessor :create_id
|
74
|
+
end
|
75
|
+
self.create_id = 'json_class'
|
76
|
+
|
77
|
+
NaN = (-1.0) ** 0.5
|
78
|
+
|
79
|
+
Infinity = 1.0/0
|
80
|
+
|
81
|
+
MinusInfinity = -Infinity
|
82
|
+
|
83
|
+
# The base exception for JSON errors.
|
84
|
+
class JSONError < StandardError; end
|
85
|
+
|
86
|
+
# This exception is raised, if a parser error occurs.
|
87
|
+
class ParserError < JSONError; end
|
88
|
+
|
89
|
+
# This exception is raised, if the nesting of parsed datastructures is too
|
90
|
+
# deep.
|
91
|
+
class NestingError < ParserError; end
|
92
|
+
|
93
|
+
# This exception is raised, if a generator or unparser error occurs.
|
94
|
+
class GeneratorError < JSONError; end
|
95
|
+
# For backwards compatibility
|
96
|
+
UnparserError = GeneratorError
|
97
|
+
|
98
|
+
# If a circular data structure is encountered while unparsing
|
99
|
+
# this exception is raised.
|
100
|
+
class CircularDatastructure < GeneratorError; end
|
101
|
+
|
102
|
+
# This exception is raised, if the required unicode support is missing on the
|
103
|
+
# system. Usually this means, that the iconv library is not installed.
|
104
|
+
class MissingUnicodeSupport < JSONError; end
|
105
|
+
|
106
|
+
module_function
|
107
|
+
|
108
|
+
# Parse the JSON string _source_ into a Ruby data structure and return it.
|
109
|
+
#
|
110
|
+
# _opts_ can have the following
|
111
|
+
# keys:
|
112
|
+
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
|
113
|
+
# structures. Disable depth checking with :max_nesting => false, it defaults
|
114
|
+
# to 19.
|
115
|
+
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
|
116
|
+
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
|
117
|
+
# to false.
|
118
|
+
# * *create_additions*: If set to false, the Parser doesn't create
|
119
|
+
# additions even if a matchin class and create_id was found. This option
|
120
|
+
# defaults to true.
|
121
|
+
def parse(source, opts = {})
|
122
|
+
JSON.parser.new(source, opts).parse
|
123
|
+
end
|
124
|
+
|
125
|
+
# Parse the JSON string _source_ into a Ruby data structure and return it.
|
126
|
+
# The bang version of the parse method, defaults to the more dangerous values
|
127
|
+
# for the _opts_ hash, so be sure only to parse trusted _source_ strings.
|
128
|
+
#
|
129
|
+
# _opts_ can have the following keys:
|
130
|
+
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
|
131
|
+
# structures. Enable depth checking with :max_nesting => anInteger. The parse!
|
132
|
+
# methods defaults to not doing max depth checking: This can be dangerous,
|
133
|
+
# if someone wants to fill up your stack.
|
134
|
+
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
|
135
|
+
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
|
136
|
+
# to true.
|
137
|
+
# * *create_additions*: If set to false, the Parser doesn't create
|
138
|
+
# additions even if a matchin class and create_id was found. This option
|
139
|
+
# defaults to true.
|
140
|
+
def parse!(source, opts = {})
|
141
|
+
opts = {
|
142
|
+
:max_nesting => false,
|
143
|
+
:allow_nan => true
|
144
|
+
}.update(opts)
|
145
|
+
JSON.parser.new(source, opts).parse
|
146
|
+
end
|
147
|
+
|
148
|
+
# Unparse the Ruby data structure _obj_ into a single line JSON string and
|
149
|
+
# return it. _state_ is
|
150
|
+
# * a JSON::State object,
|
151
|
+
# * or a Hash like object (responding to to_hash),
|
152
|
+
# * an object convertible into a hash by a to_h method,
|
153
|
+
# that is used as or to configure a State object.
|
154
|
+
#
|
155
|
+
# It defaults to a state object, that creates the shortest possible JSON text
|
156
|
+
# in one line, checks for circular data structures and doesn't allow NaN,
|
157
|
+
# Infinity, and -Infinity.
|
158
|
+
#
|
159
|
+
# A _state_ hash can have the following keys:
|
160
|
+
# * *indent*: a string used to indent levels (default: ''),
|
161
|
+
# * *space*: a string that is put after, a : or , delimiter (default: ''),
|
162
|
+
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
|
163
|
+
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
|
164
|
+
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
|
165
|
+
# * *check_circular*: true if checking for circular data structures
|
166
|
+
# should be done (the default), false otherwise.
|
167
|
+
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
|
168
|
+
# generated, otherwise an exception is thrown, if these values are
|
169
|
+
# encountered. This options defaults to false.
|
170
|
+
# * *max_nesting*: The maximum depth of nesting allowed in the data
|
171
|
+
# structures from which JSON is to be generated. Disable depth checking
|
172
|
+
# with :max_nesting => false, it defaults to 19.
|
173
|
+
#
|
174
|
+
# See also the fast_generate for the fastest creation method with the least
|
175
|
+
# amount of sanity checks, and the pretty_generate method for some
|
176
|
+
# defaults for a pretty output.
|
177
|
+
def generate(obj, state = nil)
|
178
|
+
if state
|
179
|
+
state = State.from_state(state)
|
180
|
+
else
|
181
|
+
state = State.new
|
182
|
+
end
|
183
|
+
obj.to_json(state)
|
184
|
+
end
|
185
|
+
|
186
|
+
# :stopdoc:
|
187
|
+
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
|
188
|
+
alias unparse generate
|
189
|
+
module_function :unparse
|
190
|
+
# :startdoc:
|
191
|
+
|
192
|
+
# Unparse the Ruby data structure _obj_ into a single line JSON string and
|
193
|
+
# return it. This method disables the checks for circles in Ruby objects, and
|
194
|
+
# also generates NaN, Infinity, and, -Infinity float values.
|
195
|
+
#
|
196
|
+
# *WARNING*: Be careful not to pass any Ruby data structures with circles as
|
197
|
+
# _obj_ argument, because this will cause JSON to go into an infinite loop.
|
198
|
+
def fast_generate(obj)
|
199
|
+
obj.to_json(nil)
|
200
|
+
end
|
201
|
+
|
202
|
+
# :stopdoc:
|
203
|
+
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
|
204
|
+
alias fast_unparse fast_generate
|
205
|
+
module_function :fast_unparse
|
206
|
+
# :startdoc:
|
207
|
+
|
208
|
+
# Unparse the Ruby data structure _obj_ into a JSON string and return it. The
|
209
|
+
# returned string is a prettier form of the string returned by #unparse.
|
210
|
+
#
|
211
|
+
# The _opts_ argument can be used to configure the generator, see the
|
212
|
+
# generate method for a more detailed explanation.
|
213
|
+
def pretty_generate(obj, opts = nil)
|
214
|
+
state = JSON.state.new(
|
215
|
+
:indent => ' ',
|
216
|
+
:space => ' ',
|
217
|
+
:object_nl => "\n",
|
218
|
+
:array_nl => "\n",
|
219
|
+
:check_circular => true
|
220
|
+
)
|
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
|
+
obj.to_json(state)
|
232
|
+
end
|
233
|
+
|
234
|
+
# :stopdoc:
|
235
|
+
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
|
236
|
+
alias pretty_unparse pretty_generate
|
237
|
+
module_function :pretty_unparse
|
238
|
+
# :startdoc:
|
239
|
+
|
240
|
+
# Load a ruby data structure from a JSON _source_ and return it. A source can
|
241
|
+
# either be a string like object, an IO like object, or an object responding
|
242
|
+
# to the read method. If _proc_ was given, it will be called with any nested
|
243
|
+
# Ruby object as an argument recursively in depth first order.
|
244
|
+
#
|
245
|
+
# This method is part of the implementation of the load/dump interface of
|
246
|
+
# Marshal and YAML.
|
247
|
+
def load(source, proc = nil)
|
248
|
+
if source.respond_to? :to_str
|
249
|
+
source = source.to_str
|
250
|
+
elsif source.respond_to? :to_io
|
251
|
+
source = source.to_io.read
|
252
|
+
else
|
253
|
+
source = source.read
|
254
|
+
end
|
255
|
+
result = parse(source, :max_nesting => false, :allow_nan => true)
|
256
|
+
recurse_proc(result, &proc) if proc
|
257
|
+
result
|
258
|
+
end
|
259
|
+
|
260
|
+
def recurse_proc(result, &proc)
|
261
|
+
case result
|
262
|
+
when Array
|
263
|
+
result.each { |x| recurse_proc x, &proc }
|
264
|
+
proc.call result
|
265
|
+
when Hash
|
266
|
+
result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
|
267
|
+
proc.call result
|
268
|
+
else
|
269
|
+
proc.call result
|
270
|
+
end
|
271
|
+
end
|
272
|
+
private :recurse_proc
|
273
|
+
module_function :recurse_proc
|
274
|
+
|
275
|
+
alias restore load
|
276
|
+
module_function :restore
|
277
|
+
|
278
|
+
# Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
|
279
|
+
# the result.
|
280
|
+
#
|
281
|
+
# If anIO (an IO like object or an object that responds to the write method)
|
282
|
+
# was given, the resulting JSON is written to it.
|
283
|
+
#
|
284
|
+
# If the number of nested arrays or objects exceeds _limit_ an ArgumentError
|
285
|
+
# exception is raised. This argument is similar (but not exactly the
|
286
|
+
# same!) to the _limit_ argument in Marshal.dump.
|
287
|
+
#
|
288
|
+
# This method is part of the implementation of the load/dump interface of
|
289
|
+
# Marshal and YAML.
|
290
|
+
def dump(obj, anIO = nil, limit = nil)
|
291
|
+
if anIO and limit.nil?
|
292
|
+
anIO = anIO.to_io if anIO.respond_to?(:to_io)
|
293
|
+
unless anIO.respond_to?(:write)
|
294
|
+
limit = anIO
|
295
|
+
anIO = nil
|
296
|
+
end
|
297
|
+
end
|
298
|
+
limit ||= 0
|
299
|
+
result = generate(obj, :allow_nan => true, :max_nesting => limit)
|
300
|
+
if anIO
|
301
|
+
anIO.write result
|
302
|
+
anIO
|
303
|
+
else
|
304
|
+
result
|
305
|
+
end
|
306
|
+
rescue JSON::NestingError
|
307
|
+
raise ArgumentError, "exceed depth limit"
|
308
|
+
end
|
309
|
+
end
|
310
|
+
|
311
|
+
module ::Kernel
|
312
|
+
# Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
|
313
|
+
# one line.
|
314
|
+
def j(*objs)
|
315
|
+
objs.each do |obj|
|
316
|
+
puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
|
317
|
+
end
|
318
|
+
nil
|
319
|
+
end
|
320
|
+
|
321
|
+
# Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
|
322
|
+
# indentation and over many lines.
|
323
|
+
def jj(*objs)
|
324
|
+
objs.each do |obj|
|
325
|
+
puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
|
326
|
+
end
|
327
|
+
nil
|
328
|
+
end
|
329
|
+
|
330
|
+
# If _object_ is string like parse the string and return the parsed result as
|
331
|
+
# a Ruby data structure. Otherwise generate a JSON text from the Ruby data
|
332
|
+
# structure object and return it.
|
333
|
+
#
|
334
|
+
# The _opts_ argument is passed through to generate/parse respectively, see
|
335
|
+
# generate and parse for their documentation.
|
336
|
+
def JSON(object, opts = {})
|
337
|
+
if object.respond_to? :to_str
|
338
|
+
JSON.parse(object.to_str, opts)
|
339
|
+
else
|
340
|
+
JSON.generate(object, opts)
|
341
|
+
end
|
342
|
+
end
|
343
|
+
end
|
344
|
+
|
345
|
+
class ::Class
|
346
|
+
# Returns true, if this class can be used to create an instance
|
347
|
+
# from a serialised JSON string. The class has to implement a class
|
348
|
+
# method _json_create_ that expects a hash as first parameter, which includes
|
349
|
+
# the required data.
|
350
|
+
def json_creatable?
|
351
|
+
respond_to?(:json_create)
|
352
|
+
end
|
353
|
+
end
|
354
|
+
# vim: set et sw=2 ts=2:
|