To convert a JSON string to a map in Ruby, you can use the JSON module, which provides the parse method to parse JSON data and convert it into a hash.
We can convert a JSON string to a map in Ruby by using the JSON module's parse method to parse the JSON string and convert it into a hash.
For example,
JSON.parse
method to parse the JSON string into a hash.require 'json'
# Define a JSON string
json_string = '{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50}'
# Parse the JSON string into a hash
my_map = JSON.parse(json_string)
# Print the resulting hash
puts 'Map from JSON string:'
my_map.each do |key, value|
puts "#{key}: #{value}"
end
Map from JSON string: 1: 10 2: 20 3: 30 4: 40 5: 50
In this tutorial, we learned How to Convert a JSON String to a Map in Ruby language with well detailed examples.