Class: JSON::Coder

Inherits:
Object show all
Defined in:
lib/json/common.rb

Overview

JSON::Coder holds a parser and generator configuration.

module MyApp
JSONC_CODER = JSON::Coder.new(
  allow_trailing_comma: true
)
end

MyApp::JSONC_CODER.load(document)

Instance Method Summary collapse

Constructor Details

#initialize(object_class: nil, array_class: nil, on_load: nil, **options, &as_json) ⇒ Coder

:call-seq:

JSON.new(options = nil, &block)

Argument options, if given, contains a Hash of 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:

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"



781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'lib/json/common.rb', line 781

def initialize(object_class: nil, array_class: nil, on_load: nil, **options, &as_json)
  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,
  ).freeze
end

Instance Method Details

#dump(object, io = nil) ⇒ Object Also known as: generate

call-seq:

dump(object) -> String
dump(object, io) -> io

Serialize the given object into a JSON document.



802
803
804
# File 'lib/json/common.rb', line 802

def dump(object, io = nil)
  @state.generate(object, io)
end

#load(source) ⇒ Object Also known as: parse

call-seq:

load(string) -> Object

Parse the given JSON document and return an equivalent Ruby object.



811
812
813
# File 'lib/json/common.rb', line 811

def load(source)
  @parser_config.parse(source)
end

#load_file(path) ⇒ Object

call-seq:

load(path) -> Object

Parse the given JSON document and return an equivalent Ruby object.



820
821
822
# File 'lib/json/common.rb', line 820

def load_file(path)
  load(File.read(path, encoding: Encoding::UTF_8))
end