Open In App

How to Convert JSON to Hash in Ruby?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to convert JSON to hash in Ruby. We can convert JSON to hash through different methods ranging from parsing JSON and JSON.load to using YAML.safe_load Method.

Using JSON.parse Method

The JSON.parse method is a built-in method in Ruby’s JSON module. It parses a JSON-formatted string and converts it into a Ruby hash.

Syntax:

hash = JSON.parse(json_string)

Example:

In this example, we have a JSON-formatted string containing personal data and we use JSON.parse method parses the JSON string and converts it into a Ruby hash, assigning it to the variable hash.

Ruby
# Converting JSON to hash using JSON.parse Method

# Requiring the 'json' library to use JSON-related methods
require 'json'

# JSON-formatted string containing person data
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Parsing the JSON string and converting it into a Ruby hash
hash = JSON.parse(json_string)

# Printing the resulting hash
puts hash.inspect

Output
{"name"=>"John", "age"=>30, "city"=>"New York"}

Using JSON.load Method

The JSON.load method is also part of Ruby’s JSON module and is used to parse a JSON-formatted string and convert it into a Ruby hash.

Syntax:

hash = JSON.load(json_string)

Example: 

In this example we create a JSON-formatted string json_string containing fruit data and use JSON.load(json_string) to parse the JSON string and converts it into a Ruby hash.

Ruby
# Converting JSON to hash using  JSON.load Method

# Requiring the 'json' library to use JSON-related methods
require 'json'

# JSON-formatted string containing fruit data
json_string = '{"fruit": "Apple", "color": "Red", "quantity": 5}'

# Parsing the JSON string and converting it into a Ruby hash
hash = JSON.load(json_string)

# Printing the resulting hash
puts hash.inspect

Output
{"fruit"=>"Apple", "color"=>"Red", "quantity"=>5}

Using YAML.safe_load Method

The YAML.safe_load Method parse JSON data into a hash

Syntax:

hash = YAML.safe_load(json_string)

Example: 

In this example we create a JSON-formatted string json_string containing fruit data and use YAML.safe_load(json_string) to parse the JSON string and converts it into a Ruby hash.

Ruby
# Converting JSON to hash using YAML.safe_load Method

# Requiring the 'yaml' library to use YAML.safe_load
require 'yaml'

# Sample JSON-formatted string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Parsing the JSON string and converting it into 
hash = YAML.safe_load(json_string)


# Printing the resulting hash
puts hash.inspect

Output
Method 6 Output:
{"name"=>"John", "age"=>30, "city"=>"New York"}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads