How to use JSON.load Method In JSON

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}

How to Convert JSON to Hash in Ruby?

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.

Table of Content

  • Using JSON.parse Method
  • Using JSON.load Method
  • Using YAML.safe_load Method

Similar Reads

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....

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....

Using YAML.safe_load Method

The YAML.safe_load Method parse JSON data into a hash...

Contact Us