我有一个看起来像这样的JSON数组:
response = {
"items"=>[
{
"tags"=>[
"random"
],
"timestamp"=>12345,
"storage"=>{
"url"=>"https://example.com/example",
"key"=>"mykeys"
},
"envelope"=>{
},
"log-level"=>"info",
"id"=>"random_id_test_1",
"campaigns"=>[
],
"user-variables"=>{
},
"flags"=>{
"is-test-mode"=>false
},
"message"=>{
"headers"=>{
"to"=>"random@example.com",
"message-id"=>"foobar@example.com",
"from"=>"noreply@example.com",
"subject"=>"new subject"
},
"attachments"=>[
],
"recipients"=>[
"result@example.com"
],
"size"=>4444
},
"event"=>"stored"
},
{
"tags"=>[
"flowerPower"
],
"timestamp"=>567890,
"storage"=>{
"url"=>"https://yahoo.com",
"key"=>"some_really_cool_keys_go_here"
},
"envelope"=>{
},
"log-level"=>"info",
"id"=>"some_really_cool_ids_go_here",
"campaigns"=>[
],
"user-variables"=>{
},
"flags"=>{
"is-test-mode"=>false
},
"message"=>{
"headers"=>{
"to"=>"another_great@example.com",
"message-id"=>"email_id@example.com",
"from"=>"from@example.com",
"subject"=>"email_looks_good"
},
"attachments"=>[
],
"recipients"=>[
"example@example.com"
],
"size"=>2222
},
"event"=>"stored"
}]
}
我正在尝试根据"storage"
电子邮件获取"url"
"to"
。
如何遍历此数组,其中x
只是数组中的元素
response['items'][x]["message"]["headers"]["to"]
找到我需要的特定电子邮件后,它会停止并返回x
的值,即元素编号。
我打算将此值用于x
并致电response['items'][x]['storage']['url']
这将返回URL的字符串。
我想过这样做但是必须有一个更好的方法:
x = 0
user_email = another_great@example.com
while user_email != response['items'][x]["message"]["headers"]["to"] do
x+=1
value = x
puts value
end
答案 0 :(得分:2)
target =
response['items'].detect do |i|
i['message']['headers']['to'] == 'another_great@example.com'
end
然后
target['storage']['url']
答案 1 :(得分:1)
这是使用to's email
键创建哈希的另一种选择。并在此基础上获取所需的信息:
email_hash = Hash.new
response["items"].each do |i|
email_hash[i["message"]["headers"]["to"]] = i
end
现在,如果您想要抓取"storage"
"url"
,请执行以下操作:
user_email = "another_great@example.com"
puts email_hash[user_email]["storage"]["url"] if email_hash[user_email]
#=> "https://yahoo.com"
答案 2 :(得分:0)
您可以将其用作@Satoru建议。作为一个建议,如果你使用案例涉及对json数据的复杂查询(比这更复杂),那么你可以将你的数据存储在mongodb中,并且可以优雅地查询任何内容。