从 ruby 中的 json 获取特定的键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5348449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a particular key value from json in ruby
提问by Anand Soni
[
"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.
上面是我的 json 对象,它是作为响应来的。
How do I get SUB_KEY1of KEY1and SUB_KEY1of KEY2in Ruby on Rails?
我如何获得SUB_KEY1的KEY1和SUB_KEY1的KEY2在Ruby on Rails的?
Thank you.
谢谢你。
采纳答案by Rishav Rastogi
parsed_json = ActiveSupport::JSON.decode(your_json_string)
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"]
您应该能够使用类似的东西访问它 parsed_json[1]["KEY2"]["SUB_KEY1"]
回答by Jacob
You need to parse the JSON object into a ruby hash. Assuming your JSON response is called res:
您需要将 JSON 对象解析为 ruby 哈希。假设您的 JSON 响应称为 res:
require 'json'
obj = JSON.parse(res)
sv1 = obj['KEY1']['SUB_KEY1']
etc.
等等。

