Forked from potatosalad/Ruby script to convert CSV to YAML
Last active
July 11, 2018 01:06
-
-
Save PyYoshi/2dd5a68d604f3dd0d326c713477be302 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
# | |
# Originally written by http://redartisan.com/tags/csv | |
# Added and minor changes by Gavin Laking | |
# Rewritten by Andrew Bennett for Ruby 1.9 | |
# | |
# Usage: ruby csv_to_fixture.rb file.csv [--json] | |
# | |
# "id","name","mime_type","extensions","icon_url" | |
# "1","unknown","unknown/unknown","||","/images/icon/file_unknown.gif" | |
# "2","image/tiff","image/tiff","|tiff|tif|","/images/icon/blank.png" | |
# | |
# if you want to remove the id: "number" line from the resulting YAML file | |
# do a find and replace for: ^( id: \"\d*\"\n) in Textmate | |
require 'csv' | |
require 'json' | |
require 'yaml' | |
input = ARGV.shift | |
is_file = (input.nil? ? false : File.exist?(input)) | |
file = is_file ? input : STDIN | |
doc = is_file ? CSV.read(file) : CSV.parse(file.read) | |
fields = doc.shift | |
records = Array.new | |
doc.each_with_index do |row, i| | |
record = Hash.new | |
fields.each_with_index do |field, j| | |
if field == "id" || field.end_with?("_id") then | |
record[field] = row[j].to_i | |
else | |
record[field] = row[j] | |
end | |
end | |
records.push(record) | |
end | |
flag = ARGV.shift unless input.nil? | |
flag ||= input || '--yaml' | |
case flag | |
when '--json' then | |
puts records.to_json | |
else | |
puts records.to_yaml | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment