迭代JSON数组并找到所有匹配的值

时间:2015-09-24 16:41:00

标签: arrays ruby regex factory-bot

因此,我尝试使用域example.com

的电子邮件查找下面json数组中的所有元素

使用的JSON数组:

[{"addedAt"=>123456,
  "vid"=>123456,
  "canonical-vid"=>123456,
  "merged-vids"=>[],
  "portal-id"=>123456,
  "is-contact"=>true,
  "profile-token"=>"portal-token-goes-here",
  "profile-url"=>"portal-url-goes-here",
  "properties"=>{"firstname"=>{"value"=>"Ramon"}, "lastmodifieddate"=>{"value"=>"12345"}, "company"=>{"value"=>"Some Company"}, "lastname"=>{"value"=>"Carleones"}},
  "form-submissions"=>
   [{"conversion-id"=>"some-convo-id-goes-here",
     "timestamp"=>123456,
     "form-id"=>"form-id-goes-here",
     "portal-id"=>405406,
     "page-url"=>"page-url-goes-here",
     "content-type"=>"standard-page",
     "page-title"=>"page-title-goes-here",
     "title"=>"title-goes-here",
     "first-visit-url"=>"first-visit-url-goes-here",
     "first-visit-timestamp"=>123456,
     "meta-data"=>[]}],
  "identity-profiles"=>
   [{"vid"=>123456,
     "saved-at-timestamp"=>123456,
     "deleted-changed-timestamp"=>0,
     "identities"=>[{"type"=>"EMAIL", "value"=>"ramon@example.com", "timestamp"=>123456}, {"type"=>"Important", "value"=>"some-value", "timestamp"=>123456}]}],
  "merge-audits"=>[]},
 {"addedAt"=>123456,
  "vid"=>123456,
  "canonical-vid"=>123456,
  "merged-vids"=>[],
  "portal-id"=>123456,
  "is-contact"=>true,
  "profile-token"=>"portal-token-goes-here",
  "profile-url"=>"profile-url-goes-here",
  "properties"=>{"firstname"=>{"value"=>"Sally"}, "lastmodifieddate"=>{"value"=>"123456"}, "company"=>{"value"=>"Acme Inc."}, "lastname"=>{"value"=>"Jackson"}},
  "form-submissions"=>
   [{"conversion-id"=>"some-convo-id-goes-here",
     "timestamp"=>123456,
     "form-id"=>"some-form-id",
     "portal-id"=>123456,
     "title"=>"Big Freakin Title",
     "meta-data"=>[]}],
  "identity-profiles"=>
   [{"vid"=>123456,
     "saved-at-timestamp"=>123456,
     "deleted-changed-timestamp"=>0,
     "identities"=>[{"type"=>"EMAIL", "value"=>"sjackson@acme-example.com", "timestamp"=>123456}, {"type"=>"Team Lead", "value"=>"some-value", "timestamp"=>123456}]}],
  "merge-audits"=>[]
  }]

这是我尝试的代码: 我使用了工厂女孩并使用了一个实例变量:

#@json_array.contacts_obtained is a hash - contacts_obtained is the key, and the 
#value is the actual json array above.

      @json_array.contacts_obtained.detect do |i| i['identity-profiles'][0]['identities'][0]['value'] == /@example.com/
puts i
end

我不确定那样做那样的正则表达式是否可以。当我尝试时,它似乎不起作用。所以我想知道是否有另一种方法可以做到这一点。

我正在尝试使用@ example.com域获取所有元素,以便我可以“弹出”#39;他们或从json数组中删除它们。基本上我需要一个过滤器。这将使用某些域电子邮件过滤掉所有数组元素。

1 个答案:

答案 0 :(得分:2)

你快到了。使用=~代替==我想要将字符串与正则表达式匹配:

@json_array.contacts_obtained.select do |i| 
  i['identity-profiles'][0]['identities'][0]['value'] =~ /@example.com/
end