Anand Soni
Anand Soni

Reputation: 5110

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.

Upvotes: 31

Views: 80324

Answers (3)

Ashwini Padwal
Ashwini Padwal

Reputation: 21

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

Upvotes: 1

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

parsed_json = ActiveSupport::JSON.decode(your_json_string)

will parse your string as

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

You should be able to access it using something like parsed_json[1]["KEY2"]["SUB_KEY1"]

Upvotes: 25

Jacob
Jacob

Reputation: 1536

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.

Upvotes: 51

Related Questions