我有一个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"电子邮件的"to" "url"。如何迭代这个数组,其中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发布于 2015-08-27 22:33:53
target =
response['items'].detect do |i|
i['message']['headers']['to'] == 'another_great@example.com'
end然后
target['storage']['url']发布于 2015-08-28 06:11:00
这是使用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"发布于 2015-08-28 06:46:28
你可以像萨多鲁建议的那样使用它。作为建议,如果用例涉及对json数据的复杂查询(比此更复杂),则可以将数据存储在mongodb中,并且可以优雅地查询任何内容。
https://stackoverflow.com/questions/32260342
复制相似问题