How to Parse a JSON String in Ruby?

Find out how to parse a serialized JSON object in Ruby

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'] # String
puts data['age'] # Integer

The JSON.parse() method is able to make the following JSON transformations:

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 # Hash
require 'json'

data = JSON.parse('["foo", "bar"]')

# array -> Array
puts data # ["foo", "bar"]
puts # Array
require 'json'

data = JSON.parse('{"foo": "bar"}')

# string -> String
puts data['foo'] # "bar"
puts data['foo'] # String
require 'json'

data = JSON.parse('{"foo": 2, "bar": 1.5}')

# number (int) -> Integer
puts data['foo'] # 2
puts data['foo'] # Integer

# number (real) -> Float
puts data['bar'] # 1.5
puts data['bar'] # Float
require 'json'

data = JSON.parse('{"foo": true, "bar": false}')

# true -> true
puts data['foo'] # true
puts data['foo'] # TrueClass

# false -> false
puts data['bar'] # false
puts data['bar'] # FalseClass
require 'json'

data = JSON.parse('{"foo": null}')

# null -> nil
puts data['foo'] # nil
puts data['foo'] # 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:

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'] # Float

# Infinity -> Infinity
puts data['bar']  # Infinity
puts data['bar'] # Float

# -Infinity -> -Infinity
puts data['baz']  # -Infinity
puts data['baz'] # Float

Hope you found this post useful. It was published . Please show your love and support by sharing this post.