Created
February 9, 2024 11:09
-
-
Save ismasan/f69d339619ff66197f81b07eb90b8d8c to your computer and use it in GitHub Desktop.
Script to convert JSON array to CSV rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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