Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
JSON#parse
JSON.parse(source, opts) → object
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.3.0/ext/json/lib/json/common.rb, line 218
def parse(source, opts = {})
Parser.new(source, **(opts||{})).parse
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 = <<-EOT { "name": "Dave", "age" :40, "hats": [ "Cattleman's", "Panama", "Tophat" ] } EOT 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('')
See also
#parse!
#merge_dump_options
#load_file!
#pretty_generate
also in
4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0