You can parse a JSON string in Ruby using the JSON#parse()
method, which deserializes the JSON string to equivalent Ruby data structures. You can use it like so:
require 'json'
data = JSON.parse('{"name": "John Doe", "age": 29}')
puts data['name'] # "John Doe"
puts data['age'] # 29
To see the types of the decoded objects, you can get the class name of the objects like so:
puts data['name'].class.name # String
puts data['age'].class.name # Integer
The JSON.parse()
method is able to make the following JSON transformations:
JSON | Ruby |
---|---|
object |
Hash |
array |
Array |
string |
String |
number (int) |
Integer |
number (real) |
Float |
true |
true |
false |
false |
null |
nil |
For example:
require 'json'
data = JSON.parse('{"foo":"bar"}')
# object -> Hash
puts data # {'foo': 'bar'}
puts data.class.name # Hash
require 'json'
data = JSON.parse('["foo", "bar"]')
# array -> Array
puts data # ["foo", "bar"]
puts data.class.name # Array
require 'json'
data = JSON.parse('{"foo": "bar"}')
# string -> String
puts data['foo'] # "bar"
puts data['foo'].class.name # String
require 'json'
data = JSON.parse('{"foo": 2, "bar": 1.5}')
# number (int) -> Integer
puts data['foo'] # 2
puts data['foo'].class.name # Integer
# number (real) -> Float
puts data['bar'] # 1.5
puts data['bar'].class.name # Float
require 'json'
data = JSON.parse('{"foo": true, "bar": false}')
# true -> true
puts data['foo'] # true
puts data['foo'].class.name # TrueClass
# false -> false
puts data['bar'] # false
puts data['bar'].class.name # FalseClass
require 'json'
data = JSON.parse('{"foo": null}')
# null -> nil
puts data['foo'] # nil
puts data['foo'].class.name # NilClass
In addition to these, you can make Ruby decode NaN
, Infinity
and -Infinity
as well (even though they're not valid JSON). You can do so by passing the allow_nan
option as the second (optional) argument to the JSON#parse()
method, making the following JSON-to-Ruby transformations possible:
JSON | Ruby |
---|---|
NaN |
NaN |
Infinity |
Infinity |
-Infinity |
-Infinity |
For example:
require 'json'
json_str = '{"foo": NaN, "bar": Infinity, "baz": -Infinity}'
data = JSON.parse(json_str, { allow_nan: true })
# NaN -> NaN
puts data['foo'] # NaN
puts data['foo'].class.name # Float
# Infinity -> Infinity
puts data['bar'] # Infinity
puts data['bar'].class.name # Float
# -Infinity -> -Infinity
puts data['baz'] # -Infinity
puts data['baz'].class.name # Float
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.