简体   繁体   中英

Filter data in JSON string

I have a JSON string as pulled from some API

[{"_id"=>"56aefb3b653762000b400000", "checkout_started_at"=>"2016-02-01T07:32:09.120+01:00", "created_at"=>"2016-02-01T07:29:15.695+01:00", ...}]

I want to filter data in this string based on created_at , eg letting the user chose a specific date-range and then only show the data from this range.

Eg

@output = my_json.where(created_at: start_date..end_date)

My first thought was to somehow transfer the JSON string to Hashie , to interact with JSON as the data were objects:

my_json = (my_json).map { |hash| Hashie::Mash.new(hash) }

but that didn't work out

undefined method `where' for Array:0x007fd0bdeb84e0

How can I filter out data from a JSON string based on specific criteria or even SQL queries?

This simplest possible way would be to use Enumberable#select directly on the array of hashes:

require 'time'
myjson.select { |o| Time.iso8601(o["created_at"]).between?(start_date, end_date) }

If you want a fancy interface surrounding the raw data:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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