Skip to content

Instantly share code, notes, and snippets.

@3limin4t0r
Last active January 10, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3limin4t0r/e1471b051080e8f96acaee5faca369d3 to your computer and use it in GitHub Desktop.
Save 3limin4t0r/e1471b051080e8f96acaee5faca369d3 to your computer and use it in GitHub Desktop.
require 'csv'
require 'date'
require 'json'
require 'ostruct'
json = <<~JSON
[{
"key" : "foo",
"doc_count" : 3916075,
"interval" : {
"buckets" : [
{ "month" : "2019-02-01", "doc_count" : 186904 },
{ "month" : "2019-03-01", "doc_count" : 196961 }
]
}
}, {
"key" : "bar",
"doc_count" : 168089,
"interval" : {
"buckets" : [
{ "month" : "2019-01-01", "doc_count" : 8876 },
{ "month" : "2019-04-01", "doc_count" : 8694 }
]
}
}]
JSON
topics = JSON.parse(json, object_class: OpenStruct)
months = topics.flat_map { |item| item.interval.buckets }.map(&:month)
months.uniq!
months.sort_by! { |month| Date.iso8601(month) }
csv = CSV.generate do |csv|
csv << ['topic', *months]
topics.each do |topic|
buckets = topic.interval.buckets
doc_count = buckets.map(&:month).zip(buckets.map(&:doc_count)).to_h
doc_count.default = 0
csv << [topic.key, *months.map(&doc_count)]
# newest feature used Hash#to_proc ^ introduced in 2.3.0
end
end
puts csv
# prints:
#
# topic,2019-01-01,2019-02-01,2019-03-01,2019-04-01
# foo,0,186904,196961,0
# bar,8876,0,0,8694
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment