How to use JSON.parse Method In JSON
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.
Syntax:
hash = JSON.parse(json_string)
Example:
In this example, we have a JSON-formatted string containing personal data and we use JSON.parse
method parses
the JSON string and converts it into a Ruby hash, assigning it to the variable hash
.
# Converting JSON to hash using JSON.parse Method
# Requiring the 'json' library to use JSON-related methods
require 'json'
# JSON-formatted string containing person data
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Parsing the JSON string and converting it into a Ruby hash
hash = JSON.parse(json_string)
# Printing the resulting hash
puts hash.inspect
Output
{"name"=>"John", "age"=>30, "city"=>"New York"}
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
Contact Us