Skip to content

Instantly share code, notes, and snippets.

@amir20
Created March 15, 2012 01:10
Show Gist options
  • Save amir20/2040955 to your computer and use it in GitHub Desktop.
Save amir20/2040955 to your computer and use it in GitHub Desktop.
Converts YAML to CSV
#!/usr/bin/ruby
if ARGV.size.zero?
puts %Q[
Usage:
./to_csv.rb file.yml > out.csv
]
exit
end
require 'yaml'
def traverse(obj, keys = [], &block)
case obj
when Hash
obj.each do |k,v|
keys << k
traverse(v, keys, &block)
keys.pop
end
when Array
obj.each { |v| traverse(obj, keys, &block) }
else
yield keys, obj
end
end
hash = YAML.load(File.open(ARGV.first))
puts "YAML KEY,VALUE,RECOMMENDATION"
traverse(hash) do |keys, value|
if value =~ /^(.+)?(\/\*\s*(.+?)\s*\*\/)$/
puts '"' + [keys * '.', $1.strip, $3.strip] * '","' + '"'
else
puts '"' + [keys * '.', value] * '","' + '"'
end
end
@Coeur2Boeuf
Copy link

Coeur2Boeuf commented Jan 18, 2020

Hi,

Just a little bug, when Array detected.

Line 22: replace

obj.each { |v| traverse(obj, keys, &block) }

to

obj.each { |v| traverse(v, keys, &block) }

Example for this YAML :


en:
items:
- i1
- i2
- i3

Thank's for your code !

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