CodeSampleX

Sample

json 2.9.1: Enforce JSON gem 2.x top-level scalar serialization, distinguish symbolize_names from symbolize_keys, and handle IO stream return values and empty string defaults in JSON.load

Verified sample for gem json 2.9.1: Enforce JSON gem 2.x top-level scalar serialization, distinguish symbolize_names from symbolize_keys, and handle IO…

sha256:11b68ca217837cb2a5baf3ef7bd8bda4524866b9eccedef9840bab91c2e1098f

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
2
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-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

Case

HOW
Goal
Enforce JSON gem 2.x top-level scalar serialization, distinguish symbolize_names from symbolize_keys, and handle IO stream return values and empty string defaults in JSON.load
Packages
Symbols
  • JSON.generate
  • JSON.parse
  • JSON.load
  • JSON.dump
  • JSON::ParserError
  • JSON::NestingError
Environment
ruby
Created
2026-08-17T02:44:27Z

Contract

  1. assert JSON.generate and JSON.parse serialize and deserialize top-level primitive strings, numbers, booleans, and nil directly without quirks mode, while symbolize_keys is silently ignored leaving string keys unless symbolize_names is used
  2. assert JSON.load with an empty string returns nil via default allow_blank but raises JSON::ParserError on non-empty whitespace, whereas JSON.parse raises JSON::ParserError on both
  3. assert JSON.dump with an IO destination writes the payload and returns the IO instance itself rather than the generated JSON string
  4. assert JSON.dump depth limit violation raises ArgumentError whereas JSON.generate depth limit violation raises JSON::NestingError
  5. assert JSON.dump with keyword arguments like indent raises ArgumentError for unknown keywords instead of configuring pretty printing

Files

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/json_v2_core.rb
  • test/contract.rb

Download the source artifact (tar.gz)

Source

Gemfile
source "https://rubygems.org"

gem "json", "2.9.1"
gem "minitest", "5.27.0"
Gemfile.lock
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
NOTES.md
# Notes on Ruby JSON gem v2 behavior

## 1. What `search_known_solution` answered
`search_known_solution` returned existing matches:
- `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 Oj fallback, `to_json` receiving `JSON::State`, `allow_nan`, and decimal loss.
- `sha256:df4aa35ee31c7f410ee0b28bc36fb57ed4097f3aa8f1bf2fdae342d6841dfe00`: focused on 2.8/2.9 minor boundary changes (`script_safe` CJK 3-byte preservation, `allow_trailing_comma`, empty collection formatting in `pretty_generate`, and `GeneratorError#invalid_object`).
- `sha256:bf14ddbf0fcd9e136f9c2756bcecadc65db71791ad78d4e868a2301637151314`: focused on `JSON.load` parameter binding collisions, `max_nesting: 0` bypass, `freeze: true`, and `script_safe`.
- `sha256:be8631ddd8260e299bc9e0e9cd94448cb7367b793dfa603ea1085c293b59193c`: focused on `JSON.parse!` vs `JSON.parse`, `json/add/*` core types, and `JSON::State` generation.
- `sha256:9827be1e0572cc3101b9a4e869987b07ce9ec8eb700a514eef6a1354b17ff7e9`: focused on `JSON.dump` signature, `create_additions` vs `symbolize_names` in `JSON.load`, and `object_class` protocol.

This sample focuses on the major architectural transition in JSON gem 2.x:
1. Native top-level scalar generation and parsing (RFC 7159) without `quirks_mode`.
2. Silent ignoring of `symbolize_keys: true` (a common ActiveSupport habit) in favor of `symbolize_names: true`.
3. `JSON.load` empty string handling (`""` returns `nil` via `allow_blank`, while whitespace `"   "` raises `JSON::ParserError`).
4. `JSON.dump` returning the destination `IO` stream object rather than a `String`.
5. Depth limit error distinction (`ArgumentError: exceed depth limit` in `JSON.dump` vs `JSON::NestingError` in `JSON.generate`).

## 2. What a model would have written instead
A model would assume top-level primitives like `JSON.generate("hello")` or `JSON.parse("42")` require `quirks_mode: true` or array/hash encapsulation as in JSON gem 1.x, pass `symbolize_keys: true` expecting symbol keys, expect `JSON.dump(payload, io)` to return the generated JSON string, or expect depth limit violations in `JSON.dump` to raise `JSON::NestingError`.

## 3. How the wrong version fails
- In JSON gem 1.x, top-level primitive parsing and generation fail loudly with `JSON::ParserError` or `JSON::GeneratorError: only generation of objects and arrays is supported!` unless `quirks_mode: true` is passed.
- `JSON.parse(source, symbolize_keys: true)` fails silently with a green build by ignoring the option and returning string keys (`{"status" => "active"}` instead of `{status: "active"}`).
csx.json
{"case":{"believed":"JSON.generate and JSON.parse reject top-level primitive scalars like strings, booleans, and numbers unless wrapped in objects or arrays, and symbolize_keys: true transforms parsed keys into Ruby symbols.","caseId":"case:sha256:e2657f4b5921e063f98c0c4499891511b28c112b9b8305db198c1b70f305bff0","contract":["assert JSON.generate and JSON.parse serialize and deserialize top-level primitive strings, numbers, booleans, and nil directly without quirks mode, while symbolize_keys is silently ignored leaving string keys unless symbolize_names is used","assert JSON.load with an empty string returns nil via default allow_blank but raises JSON::ParserError on non-empty whitespace, whereas JSON.parse raises JSON::ParserError on both","assert JSON.dump with an IO destination writes the payload and returns the IO instance itself rather than the generated JSON string","assert JSON.dump depth limit violation raises ArgumentError whereas JSON.generate depth limit violation raises JSON::NestingError","assert JSON.dump with keyword arguments like indent raises ArgumentError for unknown keywords instead of configuring pretty printing"],"goal":"Enforce JSON gem 2.x top-level scalar serialization, distinguish symbolize_names from symbolize_keys, and handle IO stream return values and empty string defaults in JSON.load","kind":"HOW","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.generate","JSON.parse","JSON.load","JSON.dump","JSON::ParserError","JSON::NestingError"]},"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.generate","JSON.parse","JSON.load","JSON.dump","JSON::ParserError","JSON::NestingError"],"verifierAdapter":"rubygems@1"}
src/json_v2_core.rb
# frozen_string_literal: true

require "json"
require "stringio"

module JsonV2Core
  # Demonstrates top-level primitive serialization supported out-of-the-box in JSON gem 2.x (RFC 7159).
  # Unlike JSON gem 1.x which required quirks_mode: true or raised GeneratorError, JSON 2.x serializes
  # primitive values (strings, numbers, booleans, nil) directly.
  def self.serialize_primitive(val)
    JSON.generate(val)
  end

  # Demonstrates top-level primitive deserialization supported in JSON gem 2.x.
  def self.parse_primitive(json_str)
    JSON.parse(json_str)
  end

  # Demonstrates symbolize_names vs symbolize_keys in JSON.parse.
  # Passing symbolize_keys: true is silently ignored in standard Ruby json,
  # while symbolize_names: true produces Symbol keys.
  def self.parse_with_symbol_keys(json_str)
    JSON.parse(json_str, symbolize_names: true)
  end

  # Demonstrates empty payload handling in JSON.load vs JSON.parse.
  # JSON.load defaults to allow_blank: true and returns nil for empty strings (""),
  # but raises JSON::ParserError when given non-empty whitespace ("   ").
  def self.load_blank_safe(source)
    JSON.load(source)
  end

  # Demonstrates JSON.dump streaming behavior: when an IO destination is provided,
  # JSON.dump writes to the IO and returns the IO object itself, not the string.
  def self.dump_to_io(obj, io)
    JSON.dump(obj, io)
  end

  # Demonstrates JSON.dump depth limit enforcement: passing an integer limit raises
  # ArgumentError ("exceed depth limit") when recursion depth is exceeded.
  def self.dump_with_depth_limit(obj, limit)
    JSON.dump(obj, limit)
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "stringio"
require_relative "../src/json_v2_core"

class JsonV2ContractTest < Minitest::Test
  def test_top_level_scalar_serialization_and_symbolize_names_distinction
    # 1. JSON gem 2.x natively serializes top-level primitive scalars (strings, numbers, booleans, nil)
    # without requiring quirks_mode or wrapping in arrays/objects.
    assert_equal '"hello"', JsonV2Core.serialize_primitive("hello")
    assert_equal "42", JsonV2Core.serialize_primitive(42)
    assert_equal "true", JsonV2Core.serialize_primitive(true)
    assert_equal "false", JsonV2Core.serialize_primitive(false)
    assert_equal "null", JsonV2Core.serialize_primitive(nil)

    # JSON.parse natively parses top-level primitives
    assert_equal "hello", JsonV2Core.parse_primitive('"hello"')
    assert_equal 42, JsonV2Core.parse_primitive("42")
    assert_equal true, JsonV2Core.parse_primitive("true")
    assert_equal false, JsonV2Core.parse_primitive("false")
    assert_nil JsonV2Core.parse_primitive("null")

    # 2. symbolize_keys vs symbolize_names:
    # Passing symbolize_keys: true is silently ignored, leaving String keys.
    ignored_opt = JSON.parse('{"status":"active","count":1}', symbolize_keys: true)
    assert_equal({ "status" => "active", "count" => 1 }, ignored_opt)
    assert_instance_of String, ignored_opt.keys.first
    refute ignored_opt.key?(:status)

    # Passing symbolize_names: true correctly converts keys to Symbols.
    symbolized = JsonV2Core.parse_with_symbol_keys('{"status":"active","count":1}')
    assert_equal({ status: "active", count: 1 }, symbolized)
    assert_instance_of Symbol, symbolized.keys.first
    assert symbolized.key?(:status)
  end

  def test_empty_string_handling_between_json_load_and_json_parse
    # JSON.load defaults to allow_blank: true (in JSON.load_default_options) and returns nil for ""
    assert_nil JsonV2Core.load_blank_safe("")
    assert_nil JSON.load("")

    # JSON.parse does NOT support allow_blank and strictly raises JSON::ParserError on empty string
    err_parse_empty = assert_raises(JSON::ParserError) do
      JSON.parse("")
    end
    assert_includes err_parse_empty.message, "unexpected token"

    # Whitespace-only string "   " is not empty (source.empty? is false),
    # so JSON.load attempts to parse it and raises JSON::ParserError
    err_load_ws = assert_raises(JSON::ParserError) do
      JSON.load("   ")
    end
    assert_includes err_load_ws.message, "unexpected token"

    err_parse_ws = assert_raises(JSON::ParserError) do
      JSON.parse("   ")
    end
    assert_includes err_parse_ws.message, "unexpected token"
  end

  def test_json_dump_io_return_value_and_streaming
    payload = { "service" => "auth", "ready" => true }
    io_dest = StringIO.new

    # When IO is passed to JSON.dump, it writes the serialized JSON to the IO stream
    # and returns the IO object itself, rather than the formatted string.
    result = JsonV2Core.dump_to_io(payload, io_dest)
    assert_same io_dest, result
    assert_equal '{"service":"auth","ready":true}', io_dest.string

    # When no IO is passed, JSON.dump returns the serialized string directly
    str_result = JSON.dump(payload)
    assert_instance_of String, str_result
    assert_equal '{"service":"auth","ready":true}', str_result
  end

  def test_depth_limit_violation_error_types_in_dump_versus_generate
    nested = { "level1" => { "level2" => { "level3" => 42 } } }

    # JSON.dump with depth limit raises ArgumentError ("exceed depth limit")
    err_dump = assert_raises(ArgumentError) do
      JsonV2Core.dump_with_depth_limit(nested, 2)
    end
    assert_equal "exceed depth limit", err_dump.message

    # In contrast, JSON.generate with max_nesting raises JSON::NestingError
    err_gen = assert_raises(JSON::NestingError) do
      JSON.generate(nested, max_nesting: 2)
    end
    assert_includes err_gen.message, "nesting of 2 is too deep"
  end

  def test_json_dump_rejects_generator_formatting_keyword_arguments
    payload = { "key" => "value" }

    # JSON.dump signature is (obj, anIO = nil, limit = nil).
    # Passing keyword arguments like indent: "  " raises ArgumentError (unknown keyword).
    err = assert_raises(ArgumentError) do
      JSON.dump(payload, indent: "  ")
    end
    assert_includes err.message, "unknown keyword"
  end
end

Origin Seeder

csx-seed