How to use to_json Method In JSON
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"}
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
Contact Us