Class: JSON::Coder
- Inherits:
-
Object
- Object
- JSON::Coder
- Defined in:
- lib/json/common.rb
Overview
Instance Method Summary collapse
-
#dump(object, io = nil) ⇒ Object
(also: #generate)
call-seq: dump(object) -> String dump(object, io) -> io.
-
#initialize(options = nil, &as_json) ⇒ Coder
constructor
:call-seq: JSON.new(options = nil, &block).
-
#load(source) ⇒ Object
(also: #parse)
call-seq: load(string) -> Object.
-
#load_file(path) ⇒ Object
call-seq: load(path) -> Object.
Constructor Details
#initialize(options = nil, &as_json) ⇒ Coder
:call-seq:
JSON.new( = 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 encoutered, 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"
894 895 896 897 898 899 900 901 902 903 904 905 906 |
# File 'lib/json/common.rb', line 894 def initialize( = nil, &as_json) if .nil? = { strict: true } else = .dup [:strict] = true end [:as_json] = as_json if as_json [:create_additions] = false unless .key?(:create_additions) @state = State.new().freeze @parser_config = Ext::Parser::Config.new() 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.
913 914 915 |
# File 'lib/json/common.rb', line 913 def dump(object, io = nil) @state.generate_new(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.
922 923 924 |
# File 'lib/json/common.rb', line 922 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.
931 932 933 |
# File 'lib/json/common.rb', line 931 def load_file(path) load(File.read(path, encoding: Encoding::UTF_8)) end |