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.0.0/ext/json/lib/json/common.rb, line 351
def parse(source, opts = nil)
opts = ParserOptions.prepare(opts) unless opts.nil?
Parser.parse(source, opts)
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 (783: unexpected token at ''): JSON.parse('')