[英]Filter data in JSON string
我有一个从某些API中提取的JSON字符串
[{ “_id”=> “56aefb3b653762000b400000”, “checkout_started_at”=> “2016-02-01T07:32:09.120 + 01:00”, “created_at”=>“2016-02-01T07:29:15.695 + 01: 00“,...}]
我想基于created_at
过滤此字符串中的数据,例如让用户选择一个特定的日期范围,然后仅显示该范围内的数据。
例如
@output = my_json.where(created_at: start_date..end_date)
我的第一个想法是以某种方式将JSON字符串传输到Hashie
,以便与JSON交互,因为数据是对象:
my_json = (my_json).map { |hash| Hashie::Mash.new(hash) }
但这没有解决
数组:0x007fd0bdeb84e0的未定义方法'where'
如何根据特定条件甚至SQL查询从JSON字符串中过滤出数据?
最简单的方法是直接在哈希数组上使用Enumberable#select
:
require 'time'
myjson.select { |o| Time.iso8601(o["created_at"]).between?(start_date, end_date) }
如果您想要一个围绕原始数据的精美界面:
require 'time' # not needed in rails
class Order < Hashie::Mash
include Hashie::Extensions::Coercion
coerce_key :created_at, ->(v) do
return Time.iso8601(v)
end
end
class OrderCollection
def initialize(json)
@storage = json.map { |j| Order.new(j) }
end
def between(min, max)
@storage.select { |t| t.created_at.between?(min, max) }
end
end
orders = OrderCollection.new(myjson)
orders.between(Time.yesterday, Time.now)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.