json 3.0.2-java → 3.2.0-java

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4be775fd0d4221af4703313be47b36df730b542f95063025472d82386bc6f949
4
- data.tar.gz: aa1136bf72ebb55174ab30a3ddcaf908364a7e0cde743b952435a5ab59195d0a
3
+ metadata.gz: 137f00c15cef4a2c357c2e477b3a0fa23bddcca952a65c167c9d50e4aa7e54fa
4
+ data.tar.gz: 271b7709a5ed95e2a7a7317ba4d83ea326af3298987ecf75d953d51395f422a8
5
5
  SHA512:
6
- metadata.gz: 3b1da37df8ae7d0a8a40e41caed988f2b9f33c8ef147e66220e811adbc26199482189055badf0023bc5c4b8f201f2954a30cfa355cd7629604485c0424869f06
7
- data.tar.gz: 7e50467d636c6a30b701d4778650355e6856660add1de37eef2519865977107e715cf19d3bcceff288ee068b5993908535243b6b799f7bc37bd7f41b8c270d37
6
+ metadata.gz: 316d292bcb74ff5d867366743f4e7ee919f3b79baaf51ef1034f92a75dd2a481cc063e04b95e7c382e00324b3efae13ab4a53b37a78e5997d0d4a96f97a44b28
7
+ data.tar.gz: fcc784f5e92bca1b216bb3bfe2a20cc04ab8546d62d57b1717bfd87c6d1e5ecc2bb2576833c01b9c79ecf6c8a5359fd853446e570945b8eb52c273809e0b30e1
data/CHANGES.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  ### Unreleased
4
4
 
5
+ ### 2026-11-24 (3.2.0)
6
+
7
+ * The `script_safe: true` option of `JSON.generate` no longer escapes forward slashes `/`, and instead escapes script tag
8
+ openings (`<script`), script tag closing (`</script`) and HTML comments (`<!--`) as recommended by the HTML spec.
9
+ * The `script_safe: true` option of `JSON.generate` no longer escapes `U+2028` and `U+2029` given that Javascript is
10
+ now a proper subset of JSON since many years (see: https://github.com/tc39/proposal-json-superset).
11
+ * Fix `JSON::ParserError#json_path` raising `NoMethodError` when the document was parsed with `symbolize_names: true`.
12
+ * Fix `JSON.generate` not detecting duplicate keys such as `{ "1" => 1, 1 => 2 }`.
13
+ * JRuby: raise `TypeError` when a String subclass used as a Hash key has a `to_s` that doesn't return a String, like the C extension.
14
+ * JRuby and TruffleRuby: fix a stack overflow in `JSON::Coder` when `as_json` returns a Symbol for a string with invalid encoding.
15
+ * JRuby: fix `JSON::Coder` (and any frozen `JSON::State`) not being thread-safe. Each `#dump` call now uses its own nesting depth instead of mutating the shared state, which under concurrent use could make every later call raise `JSON::NestingError`.
16
+
17
+ ### 2026-10-13 (3.1.0)
18
+
19
+ * Added `rfc8785` generator option to canonicalize the output. Replaces the `json-canonicalization` with numerous correctness fixes.
20
+ * Use the `rb_len_t` type introduced in Ruby 4.1 to allow for proper 64bit support on LP64 platforms (Windows).
21
+ * JRuby: parser errors now include the position (`line`, `column` and the message suffix) as well as `json_path`, matching the C extension.
22
+ * Improved the accuracy of parser error's `line`, `column` and snipets in presence of multibyte characters.
23
+ * Fix `JSON.load` to work correctly when provided a `Zlib::GzipReader` as IO source.
24
+ * Reject non-ASCII BINARY strings during JSON generation. This was deprecated since a long time and scheduled to be removed for 3.0.
25
+
5
26
  ### 2026-09-09 (3.0.2)
6
27
 
7
28
  * Fix `JSON.load_file` and `JSON.load_file!` to load on Ruby 2.7.0 through 2.7.2, which cannot parse a leading parameter before `...`.
@@ -129,6 +150,15 @@ Numerous rarely used aliases have been removed.
129
150
  * Fix `allow_blank` parsing option to no longer allow invalid types (e.g. `load([], allow_blank: true)` now raise a type error).
130
151
  * Add `allow_invalid_escape` parsing option to ignore backslashes that aren't followed by one of the valid escape characters.
131
152
 
153
+ ### 2026-11-13 (2.18.3)
154
+
155
+ * Backport format string injection fix from 2.19.2. `CVE-2026-33210` / GHSA-3m6g-2423-7cp3.
156
+
157
+ ### 2026-11-02 (2.18.2)
158
+
159
+ * Backport handling of unescaped control characters preceeded by a backslash from 2.19.3.
160
+ GHSA-cjpr-jw2g-fw99.
161
+
132
162
  ### 2026-02-03 (2.18.1)
133
163
 
134
164
  * Fix a potential crash in very specific circumstance if GC triggers during a call to `to_json`
data/lib/json/common.rb CHANGED
@@ -80,14 +80,6 @@ module JSON
80
80
  def generator=(generator) # :nodoc:
81
81
  old, $VERBOSE = $VERBOSE, nil
82
82
 
83
- # The default proc used when the +sort_keys+ generation option is +true+.
84
- # It returns a new hash with the entries sorted by their keys.
85
- sort_keys_proc = ->(hash) { hash.sort.to_h }
86
- if defined?(::Ractor) && Ractor.respond_to?(:shareable_lambda)
87
- sort_keys_proc = Ractor.shareable_lambda(&sort_keys_proc)
88
- end
89
- generator::State.default_sort_keys_proc = sort_keys_proc
90
-
91
83
  @generator = generator
92
84
  if generator.const_defined?(:GeneratorMethods)
93
85
  generator_methods = generator::GeneratorMethods
@@ -146,7 +138,7 @@ module JSON
146
138
  # Is +nil+ when raised by JSON::ResumableParser.
147
139
  attr_reader :line
148
140
 
149
- # Column number where the parser encountered an error.
141
+ # One-based column number where the parser encountered an error, counted in Unicode codepoints.
150
142
  # Is +nil+ when raised by JSON::ResumableParser.
151
143
  attr_reader :column
152
144
 
@@ -179,10 +171,14 @@ module JSON
179
171
  when Integer
180
172
  "[#{segment}]"
181
173
  when String, Symbol
182
- if segment.match?(/\A[a-zA-Z\$\_][a-zA-Z\$\_0-9]*\z/)
174
+ segment = segment.to_s
175
+ if !segment.valid_encoding?
176
+ segment = segment.b.gsub(/["\\]/n, { '"' => '\\"', '\\' => '\\\\' }).force_encoding(Encoding::UTF_8)
177
+ %{["#{segment}"]}
178
+ elsif segment.match?(/\A[a-zA-Z\$\_][a-zA-Z\$\_0-9]*\z/)
183
179
  ".#{segment}"
184
180
  else
185
- segment = segment.to_s.gsub(/["\\]/, { '"' => '\\"', '\\' => '\\\\' })
181
+ segment = segment.gsub(/["\\]/, { '"' => '\\"', '\\' => '\\\\' })
186
182
  %{["#{segment}"]}
187
183
  end
188
184
  else
@@ -232,7 +228,7 @@ module JSON
232
228
  Fragment = Struct.new(:json) do
233
229
  def initialize(json)
234
230
  unless string = String.try_convert(json)
235
- raise TypeError, " no implicit conversion of #{json.class} into String"
231
+ raise TypeError, "no implicit conversion of #{json.class} into String"
236
232
  end
237
233
 
238
234
  super(string)
@@ -707,10 +703,10 @@ module JSON
707
703
  unless source.is_a?(String)
708
704
  if source.respond_to? :to_str
709
705
  source = source.to_str
706
+ elsif source.respond_to? :read
707
+ source = source.read
710
708
  elsif source.respond_to? :to_io
711
709
  source = source.to_io.read
712
- elsif source.respond_to?(:read)
713
- source = source.read
714
710
  end
715
711
  end
716
712
 
@@ -771,7 +767,7 @@ module JSON
771
767
  end
772
768
 
773
769
  opts = {
774
- allow_nan: true,
770
+ allow_nan: !(kwargs && kwargs[:rfc8785]),
775
771
  }
776
772
  opts[:max_nesting] = _deprecated_limit if _deprecated_limit
777
773
  opts.merge!(kwargs) if kwargs
@@ -835,7 +831,12 @@ module JSON
835
831
  #
836
832
  # puts MyApp::API_JSON_CODER.dump(Time.now.utc) # => "2025-01-21T08:41:44.286Z"
837
833
  #
838
- def initialize(object_class: nil, array_class: nil, on_load: nil, **options, &as_json)
834
+ # The conversion callback can also be passed as +as_json:+. If both are given, the block takes precedence.
835
+ # Passing +false+ or +nil+ for +strict:+ raises ArgumentError.
836
+ #
837
+ def initialize(object_class: nil, array_class: nil, on_load: nil, strict: true, **options, &as_json)
838
+ raise ArgumentError, "JSON::Coder requires strict mode" unless strict
839
+
839
840
  if object_class || array_class
840
841
  on_load = ParserOptions.on_load(on_load, object_class, array_class)
841
842
  end
@@ -847,7 +848,7 @@ module JSON
847
848
  @state = State.new(
848
849
  **generator_options,
849
850
  strict: true,
850
- as_json: as_json,
851
+ as_json: as_json || generator_options[:as_json],
851
852
  ).freeze
852
853
  end
853
854
 
@@ -54,7 +54,8 @@ module JSON
54
54
  strict: strict?,
55
55
  depth: depth,
56
56
  buffer_initial_length: buffer_initial_length,
57
- sort_keys: sort_keys
57
+ sort_keys: sort_keys,
58
+ rfc8785: rfc8785?,
58
59
  }
59
60
 
60
61
  allow_duplicate_key = allow_duplicate_key?
@@ -62,11 +63,6 @@ module JSON
62
63
  result[:allow_duplicate_key] = allow_duplicate_key
63
64
  end
64
65
 
65
- instance_variables.each do |iv|
66
- iv = iv.to_s[1..-1]
67
- result[iv.to_sym] = self[iv]
68
- end
69
-
70
66
  result
71
67
  end
72
68
 
Binary file
Binary file
data/lib/json/ext.rb CHANGED
@@ -28,17 +28,143 @@ module JSON
28
28
  end
29
29
  end
30
30
 
31
+ class << self
32
+ if defined?(::Ractor) && Ractor.respond_to?(:shareable_lambda)
33
+ def shareable_lambda(block) # :nodoc:
34
+ Ractor.shareable_lambda(&block)
35
+ end
36
+ else
37
+ def shareable_lambda(block) # :nodoc:
38
+ block
39
+ end
40
+ end
41
+
42
+ def valid_encoding?(str) # :nodoc:
43
+ str.ascii_only? || (str.encoding == Encoding::UTF_8 && str.valid_encoding?)
44
+ end
45
+
46
+ def coerce_key(key, as_json) # :nodoc:
47
+ as_json_called = false
48
+
49
+ unless String === key || Symbol === key
50
+ key = as_json.call(key, true)
51
+ as_json_called = true
52
+ end
53
+
54
+ if Symbol === key
55
+ key = key.to_s
56
+ end
57
+
58
+ unless String === key
59
+ raise GeneratorError.new("#{key.class} not allowed as object key in JSON", key)
60
+ end
61
+
62
+ unless valid_encoding?(key)
63
+ if as_json_called
64
+ raise GeneratorError.new("source sequence is illegal/malformed utf-8", key)
65
+ end
66
+
67
+ key = as_json.call(key, true)
68
+ unless String === key
69
+ raise GeneratorError.new("#{key.class} not allowed as object key in JSON", key)
70
+ end
71
+
72
+ unless Ext.valid_encoding?(key)
73
+ raise GeneratorError.new("source sequence is illegal/malformed utf-8", key)
74
+ end
75
+ end
76
+
77
+ key
78
+ end
79
+
80
+ def on_duplicate_key(hash, as_json)
81
+ set = {}
82
+ hash.each_key do |key|
83
+ key = coerce_key(key, as_json)
84
+ if set[key]
85
+ raise GeneratorError.new("detected duplicate key #{key.inspect}", key)
86
+ else
87
+ set[key] = true
88
+ end
89
+ end
90
+ end
91
+ end
92
+
31
93
  require 'json/ext/parser'
32
94
  Ext::Parser::Config = Ext::ParserConfig
33
95
  JSON.parser = Ext::Parser
34
96
 
35
- if RUBY_ENGINE == 'truffleruby'
97
+ generator = if RUBY_ENGINE == 'truffleruby'
36
98
  require 'json/truffle_ruby/generator'
37
- JSON.generator = JSON::TruffleRuby::Generator
99
+ JSON::TruffleRuby::Generator
38
100
  else
39
101
  require 'json/ext/generator'
40
- JSON.generator = Generator
102
+ Generator
41
103
  end
104
+
105
+ # The default proc used when the +sort_keys+ generation option is +true+.
106
+ # It returns a new hash with the entries sorted by their keys.
107
+ generator::State.default_sort_keys_proc = shareable_lambda(->(hash) {
108
+ hash.sort.to_h
109
+ })
110
+
111
+ # Directly lifted from Gregg Kellogg's json-canonicalization
112
+ generator::State.rfc8785_number_formatter_proc = shareable_lambda(->(num) {
113
+ if Integer === num
114
+ if num > Float::MAX || num < -Float::MAX
115
+ raise GeneratorError.new("Integer out of range for RFC 8785", num)
116
+ end
117
+ num = num.to_f
118
+ end
119
+ if num.zero?
120
+ "0"
121
+ else
122
+ if num < 0
123
+ num, sign = -num, '-'
124
+ end
125
+ native_rep = num.to_s
126
+ decimal, exponential = native_rep.split('e')
127
+ exp_val = exponential.to_i
128
+ exponential = exp_val > 0 ? ('+' + exp_val.to_s) : exp_val.to_s
129
+
130
+ integral, fractional = decimal.split('.')
131
+ fractional = fractional.sub(/0+$/, '') # Remove trailing zeros
132
+
133
+ if exp_val > 0 && exp_val < 21
134
+ while exp_val > 0
135
+ integral += fractional.to_s[0] || '0'
136
+ fractional = fractional.to_s[1..-1]
137
+ exp_val -= 1
138
+ end
139
+ exponential = nil
140
+ elsif exp_val == 0
141
+ exponential = nil
142
+ elsif exp_val < 0 && exp_val > -7
143
+ # Small numbers are shown as 0.etc with e-6 as lower limit
144
+ fractional, integral, exponential = integral + fractional.to_s, '0', nil
145
+ fractional = ("0" * (-exp_val - 1)) + fractional
146
+ end
147
+
148
+ fractional = nil if fractional.to_s.empty?
149
+ sign.to_s + integral + (fractional ? ".#{fractional}" : '') + (exponential ? "e#{exponential}" : '')
150
+ end
151
+ })
152
+
153
+ generator::State.rfc8785_sort_keys_proc = shareable_lambda(->(hash, as_json) {
154
+ converted = if as_json
155
+ hash.transform_keys { |k| Ext.coerce_key(k, as_json) }
156
+ else
157
+ hash.transform_keys(&:to_s)
158
+ end
159
+
160
+ if converted.size < hash.size
161
+ Ext.on_duplicate_key(hash, as_json)
162
+ end
163
+
164
+ converted.sort_by { |k,| k.encode(Encoding::UTF_16) }.to_h
165
+ })
166
+
167
+ JSON.generator = generator
42
168
  end
43
169
 
44
170
  if defined?(ResumableParser) # Not yet available on JRuby
@@ -37,15 +37,12 @@ module JSON
37
37
  "\x1f" => '\u001f',
38
38
  '"' => '\"',
39
39
  '\\' => '\\\\',
40
+ '<' => '\\u003c',
40
41
  }.freeze # :nodoc:
41
42
 
42
- SCRIPT_SAFE_MAP = MAP.merge(
43
- '/' => '\\/',
44
- "\u2028" => '\u2028',
45
- "\u2029" => '\u2029',
46
- ).freeze
43
+ ESCAPE_PATTERN = /["\\\x0-\x1f]/
47
44
 
48
- SCRIPT_SAFE_ESCAPE_PATTERN = /[\/"\\\x0-\x1f\u2028-\u2029]/
45
+ SCRIPT_SAFE_ESCAPE_PATTERN = Regexp.union(ESCAPE_PATTERN, /<(?=\/?script)/i, /<(?=!--)/)
49
46
 
50
47
  def self.native_type?(value) # :nodoc:
51
48
  (false == value || true == value || nil == value || String === value || Symbol === value || Array === value || Hash === value || Integer === value || Float === value || Fragment === value)
@@ -63,25 +60,16 @@ module JSON
63
60
  # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with
64
61
  # UTF16 big endian characters as \u????, and return it.
65
62
  def self.utf8_to_json(string, script_safe = false) # :nodoc:
66
- if script_safe
67
- if SCRIPT_SAFE_ESCAPE_PATTERN.match?(string)
68
- string.gsub(SCRIPT_SAFE_ESCAPE_PATTERN, SCRIPT_SAFE_MAP)
69
- else
70
- string
71
- end
63
+ pattern = script_safe ? SCRIPT_SAFE_ESCAPE_PATTERN : ESCAPE_PATTERN
64
+ if pattern.match?(string)
65
+ string.gsub(pattern, MAP)
72
66
  else
73
- if /["\\\x0-\x1f]/.match?(string)
74
- string.gsub(/["\\\x0-\x1f]/, MAP)
75
- else
76
- string
77
- end
67
+ string
78
68
  end
79
69
  end
80
70
 
81
71
  def self.utf8_to_json_ascii(original_string, script_safe = false) # :nodoc:
82
- string = original_string.b
83
- map = script_safe ? SCRIPT_SAFE_MAP : MAP
84
- string.gsub!(/[\/"\\\x0-\x1f]/n) { map[$&] || $& }
72
+ string = utf8_to_json(original_string, script_safe).b
85
73
  string.gsub!(/(
86
74
  (?:
87
75
  [\xc2-\xdf][\x80-\xbf] |
@@ -112,6 +100,8 @@ module JSON
112
100
  # while generating a JSON text from a Ruby data structure.
113
101
  class State
114
102
  singleton_class.attr_accessor :default_sort_keys_proc # :nodoc:
103
+ singleton_class.attr_accessor :rfc8785_number_formatter_proc # :nodoc:
104
+ singleton_class.attr_accessor :rfc8785_sort_keys_proc # :nodoc:
115
105
 
116
106
  def self.generate(obj, opts = nil, io = nil)
117
107
  new(opts).generate(obj, io)
@@ -125,7 +115,7 @@ module JSON
125
115
  if opts
126
116
  case
127
117
  when self === opts
128
- return opts
118
+ return opts.validate_rfc8785
129
119
  when opts.respond_to?(:to_hash)
130
120
  return new(opts.to_hash)
131
121
  when opts.respond_to?(:to_h)
@@ -144,7 +134,7 @@ module JSON
144
134
  # * *space_before*: a string that is put before a : pair delimiter (default: ''),
145
135
  # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
146
136
  # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
147
- # * *script_safe*: true if U+2028, U+2029 and forward slash (/) should be escaped
137
+ # * *script_safe*: true if forward slash (/) should be escaped
148
138
  # as to make the JSON object safe to interpolate in a script tag (default: false).
149
139
  # * *check_circular*: is deprecated now, use the :max_nesting option instead,
150
140
  # * *max_nesting*: sets the maximum level of data structure nesting in
@@ -168,6 +158,7 @@ module JSON
168
158
  @max_nesting = 100
169
159
  @sort_keys = false
170
160
  @allow_duplicate_key = false
161
+ @rfc8785 = false
171
162
  _configure(**opts) if opts
172
163
  end
173
164
 
@@ -189,13 +180,22 @@ module JSON
189
180
  attr_accessor :array_nl
190
181
 
191
182
  # This proc converts unsupported types into native JSON types.
192
- attr_accessor :as_json
183
+ attr_reader :as_json
184
+
185
+ def as_json=(value)
186
+ raise FrozenError, "can't modify frozen #{self.class}: #{inspect}" if frozen?
187
+ value = value.to_proc if !(Proc === value) && value.respond_to?(:to_proc)
188
+ unless Proc === value
189
+ raise TypeError, "as_json must be a Proc"
190
+ end
191
+ @as_json = value
192
+ end
193
193
 
194
194
  # This integer returns the maximum level of data structure nesting in
195
195
  # the generated JSON, max_nesting = 0 if no maximum is checked.
196
196
  attr_accessor :max_nesting
197
197
 
198
- # If this attribute is set to true, forward slashes will be escaped in
198
+ # If this attribute is set to true, script tags and HTML comments will be escaped in
199
199
  # all json strings.
200
200
  attr_accessor :script_safe
201
201
 
@@ -209,6 +209,9 @@ module JSON
209
209
  # desired order.
210
210
  attr_reader :sort_keys
211
211
 
212
+ # Controls whether RFC8785 (canonicalization) mode is enabled. Otherwise returns false.
213
+ attr_writer :rfc8785
214
+
212
215
  def sort_keys=(value) # :nodoc:
213
216
  type_error = false
214
217
  @sort_keys = case value
@@ -288,6 +291,27 @@ module JSON
288
291
  @strict
289
292
  end
290
293
 
294
+ # Returns true, if RFC8785 (canonicalization) mode is enabled. Otherwise returns false.
295
+ def rfc8785?
296
+ @rfc8785
297
+ end
298
+
299
+ def validate_rfc8785 # :nodoc:
300
+ if @rfc8785
301
+ option = if !@indent.empty? then :indent
302
+ elsif !@space.empty? then :space
303
+ elsif !@space_before.empty? then :space_before
304
+ elsif !@object_nl.empty? then :object_nl
305
+ elsif !@array_nl.empty? then :array_nl
306
+ elsif @ascii_only then :ascii_only
307
+ elsif @script_safe then :script_safe
308
+ elsif @allow_nan then :allow_nan
309
+ end
310
+ raise ArgumentError, "#{option} cannot be used with rfc8785" if option
311
+ end
312
+ self
313
+ end
314
+
291
315
  # Configure this State instance with the Hash _opts_, and return
292
316
  # itself.
293
317
  def configure(options)
@@ -302,10 +326,13 @@ module JSON
302
326
  end
303
327
  alias merge configure
304
328
 
329
+ # Defaults are the current values so that #configure only writes what it was given.
305
330
  private def _configure(
306
- indent: '', space: '', space_before: '', object_nl: '', array_nl: '', allow_nan: false,
307
- as_json: false, ascii_only: false, sort_keys: false, depth: 0, buffer_initial_length: 1024,
308
- allow_duplicate_key: false, script_safe: false, strict: false, max_nesting: 100
331
+ indent: @indent, space: @space, space_before: @space_before, object_nl: @object_nl,
332
+ array_nl: @array_nl, allow_nan: @allow_nan, as_json: @as_json, ascii_only: @ascii_only,
333
+ sort_keys: @sort_keys, depth: @depth, buffer_initial_length: @buffer_initial_length,
334
+ allow_duplicate_key: @allow_duplicate_key, script_safe: @script_safe, strict: @strict,
335
+ max_nesting: @max_nesting, rfc8785: @rfc8785
309
336
  )
310
337
  if depth.negative?
311
338
  raise ArgumentError, "depth must be >= 0 (got #{depth})"
@@ -321,7 +348,11 @@ module JSON
321
348
  @object_nl = object_nl || ''
322
349
  @array_nl = array_nl || ''
323
350
  @allow_nan = allow_nan || false
324
- @as_json = as_json || false
351
+ if as_json
352
+ self.as_json = as_json
353
+ else
354
+ @as_json = false
355
+ end
325
356
  @ascii_only = ascii_only || false
326
357
  self.sort_keys = sort_keys
327
358
  @depth = depth
@@ -330,7 +361,9 @@ module JSON
330
361
  @script_safe = script_safe
331
362
  @strict = strict
332
363
  @max_nesting = max_nesting || 0
333
- self
364
+ self.rfc8785 = rfc8785
365
+
366
+ validate_rfc8785
334
367
  end
335
368
 
336
369
  def allow_duplicate_key? # :nodoc:
@@ -340,13 +373,24 @@ module JSON
340
373
  # Returns the configuration instance variables as a hash, that can be
341
374
  # passed to the configure method.
342
375
  def to_h
343
- result = {}
344
- instance_variables.each do |iv|
345
- key = iv.to_s[1..-1]
346
- result[key.to_sym] = instance_variable_get(iv)
347
- end
348
-
349
- result
376
+ {
377
+ indent: @indent,
378
+ space: @space,
379
+ space_before: @space_before,
380
+ object_nl: @object_nl,
381
+ array_nl: @array_nl,
382
+ as_json: @as_json,
383
+ allow_nan: @allow_nan,
384
+ ascii_only: @ascii_only,
385
+ max_nesting: @max_nesting,
386
+ script_safe: @script_safe,
387
+ strict: @strict,
388
+ depth: @depth,
389
+ buffer_initial_length: @buffer_initial_length,
390
+ sort_keys: @sort_keys,
391
+ allow_duplicate_key: @allow_duplicate_key,
392
+ rfc8785: @rfc8785,
393
+ }
350
394
  end
351
395
 
352
396
  alias to_hash to_h
@@ -359,16 +403,14 @@ module JSON
359
403
  return dup.generate(obj, anIO) if frozen?
360
404
 
361
405
  depth = @depth
406
+ validate_rfc8785
362
407
  if @indent.empty? and @space.empty? and @space_before.empty? and @object_nl.empty? and @array_nl.empty? and
363
408
  !@ascii_only and !@script_safe and @max_nesting == 0 and (!@strict || Symbol === obj) and !@sort_keys
364
409
  result = generate_json(obj, ''.dup)
365
410
  else
366
- if @sort_keys
367
- obj = @sort_keys.call(obj)
368
- end
369
-
370
411
  result = obj.to_json(self)
371
412
  end
413
+
372
414
  JSON::TruffleRuby::Generator.valid_utf8?(result) or raise GeneratorError.new(
373
415
  "source sequence #{result.inspect} is illegal/malformed utf-8",
374
416
  obj
@@ -390,9 +432,18 @@ module JSON
390
432
  buf << '{'
391
433
  first = true
392
434
  key_type = nil
435
+ if @rfc8785
436
+ obj = State.rfc8785_sort_keys_proc.call(obj, @strict && @as_json)
437
+ elsif @sort_keys
438
+ obj = @sort_keys.call(obj)
439
+ end
393
440
  obj.each_pair do |k,v|
394
441
  if first
395
- key_type = k.class
442
+ if ::String == k.class || ::Symbol == k.class
443
+ key_type = k.class
444
+ else
445
+ JSON.send(:on_mixed_keys_hash, obj)
446
+ end
396
447
  else
397
448
  if key_type && !@allow_duplicate_key && key_type != k.class
398
449
  key_type = nil # stop checking
@@ -431,7 +482,7 @@ module JSON
431
482
  buf << obj.to_json(self)
432
483
  end
433
484
  when Integer
434
- buf << obj.to_s
485
+ buf << (@rfc8785 ? State.rfc8785_number_formatter_proc.call(obj) : obj.to_s)
435
486
  when Symbol
436
487
  if @strict
437
488
  fast_serialize_string(obj.name, buf)
@@ -500,10 +551,12 @@ module JSON
500
551
  def to_json(state = nil, *)
501
552
  state = State.from_state(state)
502
553
  depth = state.depth
503
- state.check_max_nesting
504
- json_transform(state)
505
- ensure
506
- state.depth = depth
554
+ begin
555
+ state.check_max_nesting
556
+ json_transform(state)
557
+ ensure
558
+ state.depth = depth
559
+ end
507
560
  end
508
561
 
509
562
  private
@@ -521,13 +574,25 @@ module JSON
521
574
  first = true
522
575
  key_type = nil
523
576
  indent = !state.object_nl.empty?
524
- each { |key, value|
577
+ hash = self
578
+
579
+ if state.rfc8785?
580
+ hash = State.rfc8785_sort_keys_proc.call(hash, state.strict? && state.as_json)
581
+ elsif state.sort_keys
582
+ hash = state.sort_keys.call(hash)
583
+ end
584
+
585
+ hash.each { |key, value|
525
586
  if first
526
- key_type = key.class
587
+ if ::String == key.class || ::Symbol == key.class
588
+ key_type = key.class
589
+ else
590
+ JSON.send(:on_mixed_keys_hash, hash)
591
+ end
527
592
  else
528
593
  if key_type && !state.allow_duplicate_key? && key_type != key.class
529
594
  key_type = nil # stop checking
530
- JSON.send(:on_mixed_keys_hash, self)
595
+ JSON.send(:on_mixed_keys_hash, hash)
531
596
  end
532
597
  result << delim
533
598
  end
@@ -592,10 +657,12 @@ module JSON
592
657
  def to_json(state = nil, *)
593
658
  state = State.from_state(state)
594
659
  depth = state.depth
595
- state.check_max_nesting
596
- json_transform(state)
597
- ensure
598
- state.depth = depth
660
+ begin
661
+ state.check_max_nesting
662
+ json_transform(state)
663
+ ensure
664
+ state.depth = depth
665
+ end
599
666
  end
600
667
 
601
668
  private
@@ -648,13 +715,20 @@ module JSON
648
715
 
649
716
  module Integer
650
717
  # Returns a JSON string representation for this Integer number.
651
- def to_json(*) to_s end
718
+ def to_json(state = nil, *)
719
+ if state && State.from_state(state).rfc8785?
720
+ State.rfc8785_number_formatter_proc.call(self)
721
+ else
722
+ to_s
723
+ end
724
+ end
652
725
  end
653
726
 
654
727
  module Float
655
728
  # Returns a JSON string representation for this Float number.
656
729
  def to_json(state = nil, *args)
657
730
  state = State.from_state(state)
731
+
658
732
  if infinite? || nan?
659
733
  if state.allow_nan?
660
734
  to_s
@@ -676,6 +750,8 @@ module JSON
676
750
  else
677
751
  raise GeneratorError.new("#{self} not allowed in JSON", self)
678
752
  end
753
+ elsif state.rfc8785?
754
+ State.rfc8785_number_formatter_proc.call(self)
679
755
  else
680
756
  to_s
681
757
  end
@@ -703,9 +779,18 @@ module JSON
703
779
 
704
780
  if state.strict? && state.as_json
705
781
  unless Generator.valid_encoding?(string)
706
- string = state.as_json.call(string, false)
707
- unless string.is_a?(::String)
708
- return string.to_json(state, *args)
782
+ coerced = state.as_json.call(string, false)
783
+ unless coerced.equal?(string)
784
+ # as_json is only called once, so a new string that is still
785
+ # invalid raises instead of calling it again.
786
+ coerced = coerced.name if coerced.is_a?(::Symbol)
787
+ unless coerced.is_a?(::String)
788
+ return coerced.to_json(state, *args)
789
+ end
790
+ unless Generator.valid_encoding?(coerced)
791
+ raise GeneratorError.new("source sequence is illegal/malformed utf-8", self)
792
+ end
793
+ string = coerced
709
794
  end
710
795
  end
711
796
  end
data/lib/json/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JSON
4
- VERSION = '3.0.2'
4
+ VERSION = '3.2.0'
5
5
  end
data/lib/json.rb CHANGED
@@ -118,7 +118,7 @@ require 'json/common'
118
118
  #
119
119
  # ==== Parsing Options
120
120
  #
121
- # ====== Input Options
121
+ # ===== Input Options
122
122
  #
123
123
  # Option +max_nesting+ (\Integer) specifies the maximum nesting depth allowed;
124
124
  # defaults to +100+;
@@ -214,7 +214,7 @@ require 'json/common'
214
214
  # When enabled:
215
215
  # JSON.parse('"Hell\o"', allow_invalid_escape: true) # => "Hello"
216
216
  #
217
- # ====== Output Options
217
+ # ===== Output Options
218
218
  #
219
219
  # Option +freeze+ (boolean) specifies whether the returned objects will be frozen;
220
220
  # defaults to +false+.
@@ -323,7 +323,7 @@ require 'json/common'
323
323
  #
324
324
  # ==== Generating Options
325
325
  #
326
- # ====== Input Options
326
+ # ===== Input Options
327
327
  #
328
328
  # Option +allow_nan+ (boolean) specifies whether
329
329
  # +NaN+, +Infinity+, and +-Infinity+ may be generated;
@@ -378,7 +378,7 @@ require 'json/common'
378
378
  # which may leave the process in an unrecoverable state.
379
379
  # It is highly discouraged.
380
380
  #
381
- # ====== Escaping Options
381
+ # ===== Escaping Options
382
382
  #
383
383
  # Options +script_safe+ (boolean) specifies wether <tt>'\u2028'</tt>, <tt>'\u2029'</tt>
384
384
  # and <tt>'/'</tt> should be escaped as to make the JSON object safe to interpolate in script
@@ -387,7 +387,7 @@ require 'json/common'
387
387
  # Options +ascii_only+ (boolean) specifies wether all characters outside the ASCII range
388
388
  # should be escaped.
389
389
  #
390
- # ====== Output Options
390
+ # ===== Output Options
391
391
  #
392
392
  # The default formatting options generate the most compact
393
393
  # \JSON data, all on one line and with no whitespace.
@@ -414,6 +414,14 @@ require 'json/common'
414
414
  # When +true+, keys are sorted lexicographically. When a \Proc, it receives
415
415
  # the entire \Hash and must return a \Hash with its pairs in the desired
416
416
  # order, allowing for arbitrary sort orders.
417
+ # - Option +rfc8785+ (boolean) controls whether the generated JSON will be canonicalized
418
+ # as defined in RFC8785.
419
+ # Integers are converted to Float before formatting and may be rounded.
420
+ # Integers outside the finite Float range raise JSON::GeneratorError.
421
+ # Nonempty +indent+, +space+, +space_before+, +object_nl+, or +array_nl+,
422
+ # and enabled +ascii_only+, +script_safe+, or +allow_nan+ raise ArgumentError.
423
+ # JSON.dump defaults +allow_nan+ to +false+ when +rfc8785+ is enabled.
424
+ # JSON::Fragment contents are inserted as is; the caller must ensure they are canonical.
417
425
  #
418
426
  # In this example, +obj+ is used first to generate the shortest
419
427
  # \JSON data (no whitespace), then again with all formatting options
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: json
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.2
4
+ version: 3.2.0
5
5
  platform: java
6
6
  authors:
7
7
  - Daniel Luz
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-09-09 00:00:00.000000000 Z
10
+ date: 2026-11-24 00:00:00.000000000 Z
11
11
  dependencies: []
12
12
  description: A JSON implementation as a JRuby extension.
13
13
  email: dev+ruby@mernen.com