How to use YAML.safe_load Method In JSON
The YAML.safe_load Method parse
JSON data into a hash
Syntax:
hash = YAML.safe_load(json_string)
Example:
In this example we create a JSON-formatted string json_string containing fruit data and use YAML.safe_load(json_string) to parse the JSON string and converts it into a Ruby hash.
# Converting JSON to hash using YAML.safe_load Method
# Requiring the 'yaml' library to use YAML.safe_load
require 'yaml'
# Sample JSON-formatted string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Parsing the JSON string and converting it into
hash = YAML.safe_load(json_string)
# Printing the resulting hash
puts hash.inspect
Output
Method 6 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