How to use JSON.generate Method In JSON
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}
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