我现在有一个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"}]
我有一个阵列:
id = ["1", "3"]
我想检查公共ID并打印相关名称。对于上面的例子,我希望我的输出是:
["good","best"]
我希望输出最好是一个数组。有一个简单的方法来做到这一点?我一直在编写太多代码来完成这项工作并认为它应该很容易完成。有什么建议吗?
答案 0 :(得分:0)
# 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"]
答案 1 :(得分:0)
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)
答案 2 :(得分:0)
可以这样做:
def method_name
render json: Model.pluck(:name).to_json
end