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)
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/ext/json/lib/json/common.rb, line 833
def initialize(object_class: nil, array_class: nil, on_load: nil, strict: true, **options, &as_json)
raise ArgumentError, "JSON::Coder requires strict mode" unless strict
if object_class || array_class
on_load = ParserOptions.on_load(on_load, object_class, array_class)
end
parser_options = options.slice(*PARSER_OPTIONS)
parser_options[:on_load] = on_load if on_load
@parser_config = Ext::Parser::Config.new(parser_options).freeze
generator_options = options.reject { |k, _| EXCLUDED_GENERATOR_OPTIONS.include?(k) }
@state = State.new(
**generator_options,
strict: true,
as_json: as_json || generator_options[:as_json],
).freeze
end
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.