Method: JSON.parse

Defined in:
lib/json/common.rb

.parse(source, opts = nil) ⇒ Object

:call-seq:

JSON.parse(source, opts) -> object

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:

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:

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:

source = "{\n\"name\": \"Dave\",\n  \"age\" :40,\n  \"hats\": [\n    \"Cattleman's\",\n    \"Panama\",\n    \"Tophat\"\n  ]\n}\n"
ruby = JSON.parse(source)
ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}

Raises an exception if source is not valid JSON:

# Raises JSON::ParserError (783: unexpected token at ''):
JSON.parse('')


220
221
222
# File 'lib/json/common.rb', line 220

def parse(source, opts = nil)
  Parser.parse(source, opts)
end