'Get a particular key value from json in ruby

[ 
"KEY1":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"},
"KEY2":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"}
]

The above is my json object which is coming as a response.

How do I get SUB_KEY1 of KEY1 and SUB_KEY1 of KEY2 in Ruby on Rails?

Thank you.



Solution 1:[1]

You need to parse the JSON object into a ruby hash. Assuming your JSON response is called res:

require 'json'
obj = JSON.parse(res)

sv1 = obj['KEY1']['SUB_KEY1']

etc.

Solution 2:[2]

You need to parse JSON data first. Then loop over the JSON object to access the key as follow:

@response = JSON.parse(HTTParty.get(your_url).body)
@response["data"].each do |key|
  puts data[0][key]
  puts data[0][key2]
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob
Solution 2 Bruno Rohée