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 objec开发者_运维知识库t 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.
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.
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"]
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
精彩评论