Converting string to hash using JSON parsing
The JSON.parse
method parses a JSON-formatted string and returns a hash representing the parsed data.
Syntax:
hash = JSON.parse(string)
Example: In this example, the JSON string json_string
is parsed using JSON.parse
, resulting in a hash containing the key-value pairs from the JSON data.
require 'json'
# Define a JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Convert JSON string to a hash
hash = JSON.parse(json_string)
puts hash
# Output: {"name"=>"John", "age"=>30, "city"=>"New York"}
Output
{"name"=>"John", "age"=>30, "city"=>"New York"}
How to convert String to Hash in Ruby?
In this article, we will discuss how to convert string to hash in ruby. We can convert a string to a hash through different methods ranging from parsing JSON and parsing YAML to custom string parsing.
Table of Content
- Converting string to hash using JSON parsing
- Converting string to hash using YAML parsing
- Custom String Parsing to Hash