Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

JSON::Coder.new

JSON::Coder.new(**options, &block)

Keyword arguments options, if given, are options for both parsing and generating. See Parsing Options, and Generating Options.

For generation, the strict: true option is always set. When a Ruby object with no native JSON counterpart is encountered, the block provided to the initialize method is invoked, and must return a Ruby object that has a native JSON counterpart:

Example
module MyApp
  API_JSON_CODER = JSON::Coder.new do |object|
    case object
    when Time
      object.iso8601(3)
    else
      object # Unknown type, will raise
    end
  end
end

puts MyApp::API_JSON_CODER.dump(Time.now.utc) # => "2025-01-21T08:41:44.286Z"

The conversion callback can also be passed as as_json:. If both are given, the block takes precedence. Passing false or nil for strict: raises ArgumentError.

See also #dump #generate also in 4.0