Sample
json 2.9.1: Preserve Ruby object and key types across JSON serialization boundaries without falling into as_json omission, symbolize_names and create_additions incompatibility, or silent key collision data loss
Verified sample for gem json 2.9.1: Preserve Ruby object and key types across JSON serialization boundaries without falling into as_json omission…
sha256:274b26e9f2c0a58c7a444f4d62e6bb7ca665c0f5f1069a445b9faa8adecd8b4d
This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured.
How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people.
MIT-0
Execution evidence
The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.
- Evidence basis
- Signed contract pass
- Verification receipts
- 2
- Signing keys that built it
- 1
Declared environment
ruby linux x64 ruby ruby rubygems
Verification-run environments
| Environment | Contract | Stages | Run |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-16 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | SKIPPED | compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Case
HOW- Goal
- Preserve Ruby object and key types across JSON serialization boundaries without falling into as_json omission, symbolize_names and create_additions incompatibility, or silent key collision data loss
- Packages
- Symbols
-
- JSON.parse
- JSON.generate
- JSON.create_id
- Object#to_json
- Environment
- ruby
- Created
- 2026-08-16T17:36:59Z
Contract
- assert JSON.parse raises ArgumentError when :symbolize_names and :create_additions are combined, making addition deserialization mutually exclusive with key symbolization
- assert JSON.generate ignores as_json and serializes arbitrary objects to inspect strings unless to_json is defined, while a to_json returning a Hash raises TypeError
- assert JSON.parse with create_additions: true instantiates registered domain objects via json_create, whereas custom create_id mismatch or missing json_create returns a plain Hash and uninitialized classes raise ArgumentError
- assert JSON.generate stringifies non-string hash keys where nil becomes an empty string, and colliding stringified keys silently overwrite earlier values on parse
- assert core Ruby types like Range and Symbol require json/add extensions to encode json_class structures, which default JSON.parse reads as Hash and create_additions: true restores to exact instances
Files
- Gemfile
- NOTES.md
- csx.json
- src/type_boundary.rb
- test/contract.rb
Source
# frozen_string_literal: true
source "https://rubygems.org"
gem "json", "2.9.1"
gem "minitest", "5.27.0"
# Notes on Ruby `json` Type and Serialization Boundaries
## What `search_known_solution` answered
`search_known_solution` returned three existing samples for `pkg:gem/json@2.9.1`:
1. `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") — focusing on compiler absence, `to_json` arity/state passing, `allow_nan`, and float precision.
2. `sha256:81f61fffbd1edaf62acfccc7a4acf7a0e3e88342d1b2f333a09e6d2e0592487d` ("In json >= 2.9.0, script_safe serialization avoids corrupting 3-byte CJK UTF-8 sequences...") — focusing on CJK UTF-8 bytes and `GeneratorError#invalid_object`.
3. `sha256:bf14ddbf0fcd9e136f9c2756bcecadc65db71791ad78d4e868a2301637151314` ("Configure Ruby JSON parsing and generation options across max_nesting, freeze, create_additions, and script_safe without falling into JSON.load keyword-proc collision...") — focusing on `JSON.load` signature proc collision, `max_nesting: 0`, and `freeze: true`.
This sample focuses on a different set of type boundaries and shape transformations during serialization and deserialization:
- The strict mutual exclusivity of `symbolize_names: true` and `create_additions: true` in `JSON.parse`.
- Omission of Rails-style `as_json` by standard `JSON.generate` and `TypeError` when `to_json` returns a Hash.
- Custom addition instantiation via `json_create`, custom `create_id` matching, and uninitialized constant handling.
- Hash key type erasure (`nil` -> `""`), heterogeneous key stringification, and silent data loss from key collisions.
- Core Ruby type (`Range`, `Symbol`) transformation across default vs addition-aware parsers.
## What a naive model writes instead
A naive model writes `JSON.parse(payload, symbolize_names: true, create_additions: true)` to deserialize domain objects while symbolizing leftover hash keys, relies on `as_json` for serialization with standard `JSON.generate`, or returns a `Hash` from `to_json`.
## How naive code fails
- `JSON.parse(payload, symbolize_names: true, create_additions: true)` fails **loudly** with `ArgumentError: options :symbolize_names and :create_additions cannot be used in conjunction`.
- `JSON.generate(model_defining_as_json)` fails **silently with a green build**, serializing the `#<Model:0x...>` inspect string instead of data.
- `JSON.generate(model_with_to_json_returning_hash)` fails **loudly** with `TypeError: wrong argument type Hash (expected String)`.
- `JSON.generate({ 1 => "first", "1" => "second", nil => "a", "" => "b" })` fails **silently with a green build**, emitting duplicate JSON keys where `JSON.parse` silently drops earlier entries without raising any error.
{"case":{"believed":"JSON.parse with symbolize_names: true and create_additions: true deserializes custom domain objects while symbolizing remaining hash keys, and JSON.generate serializes objects that implement as_json.","caseId":"case:sha256:6db94c88608ec6af16bcf3eca662169a56b6a058f0436a66f277dbc0b61e962c","contract":["assert JSON.parse raises ArgumentError when :symbolize_names and :create_additions are combined, making addition deserialization mutually exclusive with key symbolization","assert JSON.generate ignores as_json and serializes arbitrary objects to inspect strings unless to_json is defined, while a to_json returning a Hash raises TypeError","assert JSON.parse with create_additions: true instantiates registered domain objects via json_create, whereas custom create_id mismatch or missing json_create returns a plain Hash and uninitialized classes raise ArgumentError","assert JSON.generate stringifies non-string hash keys where nil becomes an empty string, and colliding stringified keys silently overwrite earlier values on parse","assert core Ruby types like Range and Symbol require json/add extensions to encode json_class structures, which default JSON.parse reads as Hash and create_additions: true restores to exact instances"],"goal":"Preserve Ruby object and key types across JSON serialization boundaries without falling into as_json omission, symbolize_names and create_additions incompatibility, or silent key collision data loss","kind":"HOW","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.parse","JSON.generate","JSON.create_id","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.generate","JSON.create_id","Object#to_json"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "json"
module TypeBoundary
# A custom domain model correctly implementing the Ruby JSON addition protocol.
# Requires `to_json(*args)` returning a JSON String and `self.json_create(data)`.
class UserAccount
attr_reader :username, :email, :permissions
def initialize(username, email, permissions = [])
@username = username
@email = email
@permissions = permissions
end
def to_json(*args)
{
JSON.create_id => self.class.name,
"username" => @username,
"email" => @email,
"permissions" => @permissions
}.to_json(*args)
end
def self.json_create(data)
new(data["username"], data["email"], data["permissions"])
end
def ==(other)
other.is_a?(UserAccount) &&
other.username == @username &&
other.email == @email &&
other.permissions == @permissions
end
end
# A domain model that implements `as_json` (common Rails / ActiveSupport convention).
# In standard Ruby `json`, `JSON.generate` ignores `as_json` and invokes `to_s`.
class RailsStyleModel
attr_reader :id, :title
def initialize(id, title)
@id = id
@title = title
end
def as_json(*)
{ "id" => @id, "title" => @title }
end
end
# A domain model where `to_json` mistakenly returns a Hash instead of a JSON String.
# In Ruby's C generator, returning a non-String raises TypeError.
class HashReturningModel
attr_reader :id
def initialize(id)
@id = id
end
def to_json(*)
{ "id" => @id }
end
end
# A model whose class is recorded in json_class but lacks `self.json_create`.
# `JSON.parse(..., create_additions: true)` silently returns the Hash when json_create is missing.
class UninstantiableModel
attr_reader :id
def initialize(id)
@id = id
end
def to_json(*args)
{ JSON.create_id => self.class.name, "id" => @id }.to_json(*args)
end
end
# Safely deserialize JSON containing custom addition types.
# Note: `symbolize_names: true` CANNOT be passed here without raising ArgumentError.
def self.deserialize_with_additions(json_str)
JSON.parse(json_str, create_additions: true)
end
# Parse JSON with symbolized keys for plain hash payloads.
def self.parse_symbolized(json_str)
JSON.parse(json_str, symbolize_names: true)
end
end
# frozen_string_literal: true
require "minitest/autorun"
require "json"
require "json/add/range"
require "json/add/symbol"
require_relative "../src/type_boundary"
class TypeBoundaryContract < Minitest::Test
def test_symbolize_names_and_create_additions_are_mutually_exclusive
user = TypeBoundary::UserAccount.new("alice", "alice@example.com", ["read", "write"])
serialized = JSON.generate(user)
# TRAP: A developer expects to deserialize custom domain objects while symbolizing any remaining Hash keys.
# In Ruby json gem, :symbolize_names and :create_additions cannot be combined and raise ArgumentError immediately.
err = assert_raises(ArgumentError) do
JSON.parse(serialized, symbolize_names: true, create_additions: true)
end
assert_includes err.message, "options :symbolize_names and :create_additions cannot be"
# With create_additions: true alone, domain objects are reconstructed
reconstructed = JSON.parse(serialized, create_additions: true)
assert_instance_of TypeBoundary::UserAccount, reconstructed
assert_equal user, reconstructed
# With symbolize_names: true alone, JSON additions are ignored and all keys become symbols
symbolized = JSON.parse(serialized, symbolize_names: true)
assert_instance_of Hash, symbolized
assert_equal "TypeBoundary::UserAccount", symbolized[:json_class]
assert_equal "alice", symbolized[:username]
end
def test_as_json_ignored_and_hash_returning_to_json_raises_type_error
rails_model = TypeBoundary::RailsStyleModel.new(42, "Quarterly Report")
# TRAP 1: Implementing `as_json` is an ActiveSupport convention, not standard Ruby json.
# Ruby's JSON.generate falls back to Object#to_json which emits an inspect string.
serialized_rails = JSON.generate(rails_model)
assert_match(/\A"#<TypeBoundary::RailsStyleModel:0x/, serialized_rails)
refute_includes serialized_rails, "Quarterly Report"
# TRAP 2: In Ruby, `to_json` MUST return a serialized JSON String, not a Ruby Hash.
# Returning a Hash raises TypeError during JSON generation.
hash_model = TypeBoundary::HashReturningModel.new(100)
type_err = assert_raises(TypeError) do
JSON.generate(hash_model)
end
assert_includes type_err.message, "wrong argument type Hash"
end
def test_addition_deserialization_create_id_matching_and_missing_json_create
user = TypeBoundary::UserAccount.new("bob", "bob@example.org", ["admin"])
user_json = JSON.generate(user)
# Default JSON.parse disables create_additions, returning a plain Hash with json_class key
default_parsed = JSON.parse(user_json)
assert_instance_of Hash, default_parsed
assert_equal "TypeBoundary::UserAccount", default_parsed["json_class"]
# create_additions: true reconstructs the custom object
reconstructed = JSON.parse(user_json, create_additions: true)
assert_instance_of TypeBoundary::UserAccount, reconstructed
assert_equal user, reconstructed
# Overriding create_id to another key ignores "json_class" and returns Hash
custom_id_parsed = JSON.parse(user_json, create_additions: true, create_id: "kind")
assert_instance_of Hash, custom_id_parsed
assert_equal "TypeBoundary::UserAccount", custom_id_parsed["json_class"]
# When json_class exists but does not define `self.json_create`, JSON.parse silently keeps it as a Hash
uninstantiable = TypeBoundary::UninstantiableModel.new(55)
uninstantiable_json = JSON.generate(uninstantiable)
uninstantiable_parsed = JSON.parse(uninstantiable_json, create_additions: true)
assert_instance_of Hash, uninstantiable_parsed
assert_equal "TypeBoundary::UninstantiableModel", uninstantiable_parsed["json_class"]
# When json_class references an unknown/uninitialized constant, JSON.parse raises ArgumentError
missing_class_json = '{"json_class":"UndefinedDomainEntityXYZ","id":1}'
const_err = assert_raises(ArgumentError) do
JSON.parse(missing_class_json, create_additions: true)
end
assert_includes const_err.message, "uninitialized constant UndefinedDomainEntityXYZ"
end
def test_hash_key_stringification_nil_conversion_and_silent_collision_overwrites
# JSON standard enforces string keys; non-string keys are converted via .to_s
mixed_keys = {
nil => "empty_key",
100 => "integer_key",
true => "bool_key",
:status => "symbol_key"
}
generated = JSON.generate(mixed_keys)
# nil becomes "", integer becomes "100", true becomes "true", symbol becomes "status"
assert_includes generated, '"":'
assert_includes generated, '"100":'
assert_includes generated, '"true":'
assert_includes generated, '"status":'
parsed = JSON.parse(generated)
assert_equal %w[100 status true], (parsed.keys - [""]).sort
assert_equal "empty_key", parsed[""]
assert_equal "integer_key", parsed["100"]
# TRAP: Key collisions across types cause duplicate keys in JSON output.
# The JSON parser silently retains only the LAST occurrence, dropping prior values without warning.
colliding_hash = {
"key" => "first_value",
:key => "second_value",
nil => "nil_value",
"" => "empty_string_value"
}
colliding_json = JSON.generate(colliding_hash)
assert_equal '{"key":"first_value","key":"second_value","":"nil_value","":"empty_string_value"}', colliding_json
collapsed = JSON.parse(colliding_json)
assert_equal 2, collapsed.size
assert_equal "second_value", collapsed["key"]
assert_equal "empty_string_value", collapsed[""]
end
def test_core_ruby_type_boundaries_and_selective_addition_restoration
# Core Ruby types like Range and Symbol change shape across serialization
range_val = 1..10
sym_val = :pending
# Range and Symbol with json/add/* extensions encode json_class metadata
range_json = JSON.generate(range_val)
sym_json = JSON.generate(sym_val)
assert_equal '{"json_class":"Range","a":[1,10,false]}', range_json
assert_equal '{"json_class":"Symbol","s":"pending"}', sym_json
# Default parse returns Hash
assert_instance_of Hash, JSON.parse(range_json)
assert_instance_of Hash, JSON.parse(sym_json)
# create_additions: true restores exact Range and Symbol instances
assert_equal (1..10), JSON.parse(range_json, create_additions: true)
assert_instance_of Range, JSON.parse(range_json, create_additions: true)
assert_equal :pending, JSON.parse(sym_json, create_additions: true)
assert_instance_of Symbol, JSON.parse(sym_json, create_additions: true)
end
end