Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created February 9, 2024 11:09
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 ismasan/f69d339619ff66197f81b07eb90b8d8c to your computer and use it in GitHub Desktop.
Save ismasan/f69d339619ff66197f81b07eb90b8d8c to your computer and use it in GitHub Desktop.
Script to convert JSON array to CSV rows
require 'json'
require 'csv'
# ruby json_to_csv.rb /path/to/data.json > /path/to/data.csv
#
MAP_VALUE = ->(value) {
case value
when Array
value.join('|')
when Hash
value.to_json
else
value
end
}
path = ARGV[0] || raise('Please provide a path to a CSV file')
data = JSON.parse(File.read(path))
headers = data.first&.keys
puts 'no data' and exit if headers.nil?
puts (CSV.generate do |csv|
csv << headers
data.each do |row|
r = headers.map { |h| MAP_VALUE.(row[h]) }
csv << r
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment