Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
JSON#parse
(::string source, ?::JSON::options opts) -> untyped
JSON.parse(source, opts) → object
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/ext/json/lib/json/common.rb, line 288
def parse(source, on_load: nil, object_class: nil, array_class: nil, **options)
if object_class || array_class
on_load = ParserOptions.on_load(on_load, object_class, array_class)
end
options[:on_load] = on_load if on_load
Parser.parse(source, options)
end
Returns the Ruby objects created by parsing the given source.
Argument source contains the String to be parsed.
Argument opts, if given, contains a Hash of options for the parsing. See Parsing Options.
When source is a JSON array, returns a Ruby Array:
Example
source = '["foo", 1.0, true, false, null]' ruby = JSON.parse(source) ruby # => ["foo", 1.0, true, false, nil] ruby.class # => Array
When source is a JSON object, returns a Ruby Hash:
Example
source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}' ruby = JSON.parse(source) ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil} ruby.class # => Hash
For examples of parsing for all JSON data types, see Parsing JSON.
Parses nested JSON objects:
Example
source = <<~JSON { "name": "Dave", "age" :40, "hats": [ "Cattleman's", "Panama", "Tophat" ] } JSON ruby = JSON.parse(source) ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
Raises an exception if source is not valid JSON:
Example
# Raises JSON::ParserError (unexpected character: 'invalid' at line 1 column 1): JSON.parse('invalid')