Guest User

Untitled

a guest
Jul 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.52 KB | None | 0 0
  1. require 'csv'
  2. require 'json'
  3. require "set"
  4.  
  5. json = JSON.parse(File.open(ARGV[0]).read)["results"]
  6. # Pass 1: Collect headings
  7. headings = SortedSet.new
  8. json.each do |hash|
  9. headings.merge(hash.keys)
  10. end
  11.  
  12. # Pass 2: Fill data into the headings
  13. csv_string = CSV.open(ARGV[1], "wb") do |csv|
  14. csv << headings
  15. json.each do |hash|
  16. row = {}
  17. headings.each do |heading|
  18. row[heading] = nil
  19. end
  20. hash.each do |k,v|
  21. row[k] = v.to_s.gsub(/\r\n?/, "").delete("\n").delete("\r")
  22. end
  23. csv << row.values
  24. end
  25. end
Add Comment
Please, Sign In to add comment