Skip to content

Instantly share code, notes, and snippets.

@jordan-thoms
Last active December 15, 2022 21:51
Show Gist options
  • Save jordan-thoms/5952666 to your computer and use it in GitHub Desktop.
Save jordan-thoms/5952666 to your computer and use it in GitHub Desktop.
Code to convert json to csv, with correct headings Usage: ruby convertjsoncsv.rb <input file> <output file>
require 'csv'
require 'json'
require "set"
json = JSON.parse(File.open(ARGV[0]).read)["results"]
# Pass 1: Collect headings
headings = SortedSet.new
json.each do |hash|
headings.merge(hash.keys)
end
# Pass 2: Fill data into the headings
csv_string = CSV.open(ARGV[1], "wb") do |csv|
csv << headings
json.each do |hash|
row = {}
headings.each do |heading|
row[heading] = nil
end
hash.each do |k,v|
row[k] = v.to_s.gsub(/\r\n?/, "").delete("\n").delete("\r")
end
csv << row.values
end
end
@illia108
Copy link

nice. thanks

@janetlee
Copy link

janetlee commented May 4, 2021

Thanks! It did the trick.

@vadorvatsal
Copy link

It works !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment