Exemple
json 2.9.1: Distinguish JSON.parse! relaxed parsing from JSON.parse strict limits, load explicit json/add core additions for bidirectional serialization, and forward generator State through custom to_json methods
Échantillon vérifié pour gem json 2.9.1: Distinguish JSON.parse! relaxed parsing from JSON.parse strict limits, load explicit json/add core additions for…
sha256:bc062acc906536678976cf1c339f352acd1b7ab93a8126083d2e995f58c8816b
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 2
- Clés de signature qui l’ont compilé
- 2
Environnement déclaré
ruby linux x64 ruby ruby rubygems
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-17 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Cas
HOW- Objectif
- Distinguish JSON.parse! relaxed parsing from JSON.parse strict limits, load explicit json/add core additions for bidirectional serialization, and forward generator State through custom to_json methods
- Paquets
- Symboles
-
- JSON.parse!
- JSON.parse
- JSON.generate
- JSON.pretty_generate
- JSON.fast_generate
- JSON::State
- json/add/range
- json/add/regexp
- Object#to_json
- Environnement
- ruby
- Créé
- 2026-08-17T02:43:07Z
Contrat
- assert JSON.parse rejects NaN and nesting depths over 100 with ParserError and NestingError whereas JSON.parse! relaxes limits to allow NaN and unbounded nesting by default
- assert core types like Range, Regexp, Complex, and Rational require explicit json/add modules to serialize as json_class additions and reconstruct via create_additions
- assert JSON.generate passes a JSON::State instance to custom to_json methods raising ArgumentError on arity-zero definitions unless state arguments are forwarded
- assert JSON::State enables custom whitespace and ASCII formatting while pretty_generate formats with newlines and fast_generate bypasses depth checks
Fichiers
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- src/json_protocol.rb
- test/contract.rb
Code source
source "https://rubygems.org"
gem "json", "2.9.1"
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
json (2.9.1)
minitest (5.27.0)
PLATFORMS
ruby
x64-mingw-ucrt
DEPENDENCIES
json (= 2.9.1)
minitest (= 5.27.0)
CHECKSUMS
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
json (2.9.1) sha256=d2bdef4644052fad91c1785d48263756fe32fcac08b96a20bb15840e96550d11
minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
BUNDLED WITH
4.0.18
# Ruby JSON Library Behavior: parse!, State Formatting, and Standard Type Additions
## 1. What `search_known_solution` answered
`search_known_solution` returned existing samples:
- `sha256:bec86395ce786b02c01ea89597d38d802ad97a4c997dc95aaa3f09e24aeeffe9` ("Read and write JSON in Ruby on an image with no C compiler, where oj cannot be installed, without the built-in json defaults changing the data"): focused on `to_json` receiving `JSON::State`, `allow_nan`, float vs bignum decimal precision, and C extension availability.
- `sha256:9827be1e0572cc3101b9a4e869987b07ce9ec8eb700a514eef6a1354b17ff7e9`: focused on `JSON.dump` signature mismatches, `JSON.load` `symbolize_names` / `create_additions` conflict, IO stream rejections in `JSON.parse`, and custom `object_class` mutation protocols.
- `sha256:bf14ddbf0fcd9e136f9c2756bcecadc65db71791ad78d4e868a2301637151314`: focused on `JSON.load` positional keyword-proc collision, `max_nesting: 0` limit bypass, `freeze: true`, and generator `script_safe`.
This sample covers a different set of APIs and traps:
1. `JSON.parse!` vs `JSON.parse`: the bang version is not a strict or exception-raising variant (as models assume by analogy with ActiveRecord `save!`), but a relaxed parser that enables `allow_nan: true` and `max_nesting: false` by default.
2. Standard type additions in `json/add/*`: `require "json"` alone only serializes core objects like `Range`, `Regexp`, `Complex`, and `Rational` into opaque strings; explicit loading of `json/add/range`, `json/add/regexp`, `json/add/complex`, and `json/add/rational` is required for structured `"json_class"` generation and bidirectional deserialization with `create_additions: true`.
3. Custom `to_json` arity and `JSON::State` forwarding: `JSON.generate` passes a `JSON::State` instance to `to_json`, raising `ArgumentError` if a model writes `def to_json` (0 arity) without accepting `*args`.
4. Low-level `JSON::State` whitespace and encoding configuration alongside `JSON.fast_generate` depth-check bypass.
## 2. What a model would have written instead
A model would write `JSON.parse!(doc)` expecting it to be a strict/raising parser mode, assume `(1..10).to_json` produces a structured object with `"json_class"` by default upon `require "json"`, and implement `def to_json` with 0 parameters on custom classes.
## 3. How the wrong version fails
- **Loud failure**: calling `JSON.generate(custom_obj)` where `custom_obj` defines `def to_json` (0 arguments) raises `ArgumentError: wrong number of arguments (given 1, expected 0)` because `JSON.generate` passes a `JSON::State` instance; `JSON.parse(nan_doc)` raises `JSON::ParserError: unexpected token at 'NaN...'`.
- **Silent failure with green build**: `(1..10).to_json` without `require "json/add/range"` produces `"\"1..10\""`, which parses as a plain `String` instead of reconstructing a `Range` object even when `create_additions: true` is passed.
{"case":{"believed":"JSON.parse! is an exception-raising strict mode of JSON.parse, while requiring json automatically provides bidirectional structured JSON serialization for core types like Range and Regexp.","caseId":"case:sha256:1279f8d54586bed65d9091335326830e3de627529aa26c24141d7387e19af556","contract":["assert JSON.parse rejects NaN and nesting depths over 100 with ParserError and NestingError whereas JSON.parse! relaxes limits to allow NaN and unbounded nesting by default","assert core types like Range, Regexp, Complex, and Rational require explicit json/add modules to serialize as json_class additions and reconstruct via create_additions","assert JSON.generate passes a JSON::State instance to custom to_json methods raising ArgumentError on arity-zero definitions unless state arguments are forwarded","assert JSON::State enables custom whitespace and ASCII formatting while pretty_generate formats with newlines and fast_generate bypasses depth checks"],"goal":"Distinguish JSON.parse! relaxed parsing from JSON.parse strict limits, load explicit json/add core additions for bidirectional serialization, and forward generator State through custom to_json methods","kind":"HOW","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.parse!","JSON.parse","JSON.generate","JSON.pretty_generate","JSON.fast_generate","JSON::State","json/add/range","json/add/regexp","Object#to_json"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.parse!","JSON.parse","JSON.generate","JSON.pretty_generate","JSON.fast_generate","JSON::State","json/add/range","json/add/regexp","Object#to_json"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "json"
require "json/add/range"
require "json/add/regexp"
require "json/add/complex"
require "json/add/rational"
module JsonProtocol
# Demonstrates relaxed parsing via JSON.parse! which enables allow_nan: true
# and max_nesting: false by default.
def self.parse_relaxed(source)
JSON.parse!(source)
end
# Demonstrates standard parsing via JSON.parse which strictly enforces
# max_nesting (default 100) and rejects NaN/Infinity by default.
def self.parse_strict(source)
JSON.parse(source)
end
# Demonstrates fine-grained generator formatting via JSON::State.
def self.format_custom(data, indent: " ", space: " ", space_before: " ", ascii_only: true)
state = JSON::State.new(
indent: indent,
space: space,
space_before: space_before,
object_nl: "\n",
array_nl: "\n",
ascii_only: ascii_only
)
state.generate(data)
end
# A domain model that properly implements the JSON generation protocol by
# accepting *args (which receives the JSON::State) and delegating it down.
class CustomEntity
attr_reader :id, :name, :attributes
def initialize(id, name, attributes = {})
@id = id
@name = name
@attributes = attributes
end
def to_json(*args)
{
"id" => @id,
"name" => @name,
"attributes" => @attributes
}.to_json(*args)
end
def ==(other)
other.is_a?(CustomEntity) &&
@id == other.id &&
@name == other.name &&
@attributes == other.attributes
end
end
# A domain model that defines to_json with 0 arity.
# Calling JSON.generate on this raises ArgumentError because JSON.generate
# passes a JSON::State instance to to_json.
class ZeroArityEntity
attr_reader :label
def initialize(label)
@label = label
end
def to_json
"{\"label\":#{@label.inspect}}"
end
end
end
# frozen_string_literal: true
require "minitest/autorun"
require_relative "../src/json_protocol"
class JsonProtocolContractTest < Minitest::Test
def test_json_parse_strict_limits_vs_parse_bang_relaxed_parsing
nan_doc = '{"metric":"cpu","nan_val":NaN,"pos_inf":Infinity,"neg_inf":-Infinity}'
deep_doc = "[" * 105 + "99" + "]" * 105
# 1. JSON.parse strictly enforces standards by default:
# NaN and Infinity raise JSON::ParserError
err_nan = assert_raises(JSON::ParserError) { JSON.parse(nan_doc) }
assert_match(/unexpected token at 'NaN/, err_nan.message)
# Nesting depth exceeding 100 raises JSON::NestingError
err_nesting = assert_raises(JSON::NestingError) { JSON.parse(deep_doc) }
assert_match(/nesting of 101 is too deep/, err_nesting.message)
# 2. JSON.parse! is NOT an exception-raising strict mode;
# it is a relaxed parser with allow_nan: true and max_nesting: false by default
parsed_nan = JSON.parse!(nan_doc)
assert parsed_nan["nan_val"].nan?
assert_equal 1, parsed_nan["pos_inf"].infinite?
assert_equal(-1, parsed_nan["neg_inf"].infinite?)
parsed_deep = JSON.parse!(deep_doc)
assert_equal 99, parsed_deep.flatten.first
# JsonProtocol helpers demonstrate both behaviors
assert_equal 99, JsonProtocol.parse_relaxed(deep_doc).flatten.first
assert_raises(JSON::NestingError) { JsonProtocol.parse_strict(deep_doc) }
end
def test_core_type_additions_bidirectional_serialization
range_obj = (1..10)
regexp_obj = /^[a-z]+$/i
complex_obj = Complex(3, 4)
rational_obj = Rational(5, 8)
# With json/add/* required, .to_json produces structured addition payloads with json_class
range_json = range_obj.to_json
regexp_json = regexp_obj.to_json
complex_json = complex_obj.to_json
rational_json = rational_obj.to_json
assert_equal '{"json_class":"Range","a":[1,10,false]}', range_json
assert_equal '{"json_class":"Regexp","o":1,"s":"^[a-z]+$"}', regexp_json
assert_equal '{"json_class":"Complex","r":3,"i":4}', complex_json
assert_equal '{"json_class":"Rational","n":5,"d":8}', rational_json
# Deserialization with create_additions: true restores exact native Ruby instances
restored_range = JSON.parse(range_json, create_additions: true)
assert_equal range_obj, restored_range
assert_instance_of Range, restored_range
restored_regexp = JSON.parse(regexp_json, create_additions: true)
assert_equal regexp_obj, restored_regexp
assert_equal regexp_obj.options, restored_regexp.options
assert_instance_of Regexp, restored_regexp
restored_complex = JSON.parse(complex_json, create_additions: true)
assert_equal complex_obj, restored_complex
assert_instance_of Complex, restored_complex
restored_rational = JSON.parse(rational_json, create_additions: true)
assert_equal rational_obj, restored_rational
assert_instance_of Rational, restored_rational
# Without create_additions: true, they remain plain Hashes
assert_instance_of Hash, JSON.parse(range_json)
assert_equal "Range", JSON.parse(range_json)["json_class"]
end
def test_custom_to_json_arity_and_state_forwarding
zero_arity = JsonProtocol::ZeroArityEntity.new("test-item")
# JSON.generate passes an internal JSON::State instance to to_json.
# An arity-0 to_json method raises ArgumentError during JSON.generate.
err = assert_raises(ArgumentError) do
JSON.generate(zero_arity)
end
assert_match(/wrong number of arguments \(given 1, expected 0\)/, err.message)
# A custom class accepting *args and passing them down preserves State formatting
custom_entity = JsonProtocol::CustomEntity.new(
101,
"sensor",
{ "location" => "rack-1", "temp_c" => 24.5 }
)
pretty_out = JSON.pretty_generate(custom_entity)
assert_includes pretty_out, " \"id\": 101"
assert_includes pretty_out, " \"name\": \"sensor\""
assert_includes pretty_out, " \"location\": \"rack-1\""
end
def test_json_state_fine_grained_formatting_and_fast_generate
data = { "title" => "café", "scores" => [98, 100] }
# JSON::State allows fine-grained specification of indentation, spaces, and ASCII escaping
custom_formatted = JsonProtocol.format_custom(
data,
indent: " ",
space: " ",
space_before: " ",
ascii_only: true
)
expected = "{\n \"title\" : \"caf\\u00e9\",\n \"scores\" : [\n 98,\n 100\n ]\n}"
assert_equal expected, custom_formatted
# JSON.fast_generate creates compact JSON without circularity/nesting depth tracking checks
fast_result = JSON.fast_generate(data)
assert_equal '{"title":"café","scores":[98,100]}', fast_result
# JSON.pretty_generate applies 2-space indentation and newline separators
pretty_result = JSON.pretty_generate(data)
assert_equal "{\n \"title\": \"café\",\n \"scores\": [\n 98,\n 100\n ]\n}", pretty_result
end
end