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