How to Convert Hash to JSON in Ruby?
Ruby Hash is an unordered set of data in key-value pairs. These are mutable and can store multiple data types. JSON stands for Javascript Object Notation and is a human-readable file format that is commonly used in web services and API calls. In this article, we will discuss how to convert a hash to a JSON in Ruby. Converting hash to JSON makes it easy for humans to read and write and easy for machines to parse and generate.
Table of Content
- Using to_json Method
- Using JSON.generate Method
- Using JSON.dump Method
Using to_json Method
The to_json method is provided by the JSON
module in Ruby and is used to convert a hash to JSON format.
Syntax:
hash = { key1: ‘value1’, key2: ‘value2’ }
json_string = hash.to_json
Example:
In this example, we define a hash with key-value pairs and then use to_json method to convert the hash
to a JSON-formatted string, which is then printed to the console.
require 'json'
# Define a hash
hash = { name: 'John', age: 30, city: 'New York' }
# Convert hash to JSON using to_json method
json_string = hash.to_json
puts json_string
Output
{"name":"John","age":30,"city":"New York"}
Using JSON.generate Method
JSON.generate Method is part of Ruby’s JSON
module and is used to convert a hash into a JSON-formatted string.
Syntax:
hash = { key1: ‘value1’, key2: ‘value2’ } json_string = JSON.generate(hash)
Example:
In this example, we define a hash with key-value pairs and then use JSON.generate method to convert the hash to a JSON-formatted string, which is then printed to the console.
require 'json'
# Define a hash
hash = { fruit: 'Apple', color: 'Red', quantity: 5 }
# Convert hash to JSON using JSON.generate method
json_string = JSON.generate(hash)
puts json_string
Output
{"fruit":"Apple","color":"Red","quantity":5}
Using JSON.dump Method
JSON.dump Method is is also part of Ruby’s JSON module and is used to convert a hash to JSON format.
Syntax:
hash = { key1: ‘value1’, key2: ‘value2’ } json_string = JSON.dump(hash)
Example:
In this example, we define a hash with key-value pairs and then use JSON.dump method to convert the hash to a JSON-formatted string, which is then printed to the console.
require 'json'
# Define a hash
hash = { country: 'USA', capital: 'Washington D.C.', population: 328_200_000 }
# Convert hash to JSON using JSON.dump method
json_string = JSON.dump(hash)
puts json_string
Output
{"country":"USA","capital":"Washington D.C.","population":328200000}
Contact Us