简体   繁体   English

在Ruby中获取JSON和数组之间的通用元素

[英]Getting the common elements between JSON and array in Ruby

I now have a JSON string: 我现在有一个JSON字符串:

[{"id":1,"name":"good","created_at":"2014-07-28T19:45:50.440Z","updated_at":"2014-07-28T19:45:50.440Z"},{"id":2,"name":"better","created_at":"2014-07-28T19:45:50.447Z","updated_at":"2014-07-28T19:45:50.447Z"},{"id":3,"name":"best","created_at":"2014-07-28T19:45:50.449Z","updated_at":"2014-07-28T19:45:50.449Z"}]

And I have an array: 我有一个数组:

id = ["1", "3"]

I want to check for the common IDs and print the associated name. 我想检查通用ID并打印相关名称。 For the above example I want my output to be: 对于以上示例,我希望输出为:

 ["good","best"]

I want the output preferably to be an array. 我希望输出最好是一个数组。 Is there a easy way to do this? 有没有简单的方法可以做到这一点? I have been writing too much code to get this done and feel it should be easily done. 我一直在编写太多代码来完成此操作,并认为应该轻松完成。 Any suggestions? 有什么建议么?

# initiate json string
json = %q([{"id":1,"name":"good","created_at":"2014-07-28T19:45:50.440Z","updated_at":"2014-07-28T19:45:50.440Z"},{"id":2,"name":"better","created_at":"2014-07-28T19:45:50.447Z","updated_at":"2014-07-28T19:45:50.447Z"},{"id":3,"name":"best","created_at":"2014-07-28T19:45:50.449Z","updated_at":"2014-07-28T19:45:50.449Z"}])

ids = ["1", "3"]

JSON.parse(json).select{|x| ids.include? x["id"].to_s}.map{|x| x["name"]}
#=> ["good", "best"]  

require 'json'

def pluck(json, ids)
  json_parsed = JSON.parse(json)

  json_parsed.select do |obj|
    ids.include?(obj['id'])
  end
  .map do |obj|
    obj['name']
  end
end

# usage
json = '[{"id":1,"name":"good","created_at":"2014-07-28T19:45:50.440Z","updated_at":"2014-07-28T19:45:50.440Z"},{"id":2,"name":"better","created_at":"2014-07-28T19:45:50.447Z","updated_at":"2014-07-28T19:45:50.447Z"},{"id":3,"name":"best","created_at":"2014-07-28T19:45:50.449Z","updated_at":"2014-07-28T19:45:50.449Z"}]'
ids = [1, 3]
pluck(json, ids)

in you controller can do this: 在您的控制器中可以执行以下操作:

def  method_name

  render json: Model.pluck(:name).to_json

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM