Skip to content

Instantly share code, notes, and snippets.

@Ortuna
Created September 10, 2012 18:56
Show Gist options
  • Save Ortuna/3692968 to your computer and use it in GitHub Desktop.
Save Ortuna/3692968 to your computer and use it in GitHub Desktop.
Example of when I had to convert CSV file to JSON for some content import
require 'csv'
require 'json'
require 'yaml'
normalize_names = {
"ID" => "id",
"Page Location" => "location",
"Page Body Content" => "content",
"Secondary Content" => "content_secondary",
"Title Tag" => "title",
"Meta Tag: Keywords" => "keywords",
"Meta Tag: Description" => "description",
}
content = []
urls = []
CSV.foreach("data.csv", :headers => true) do |row|
node = Hash.new
#convert old key => new key
normalize_names.each do |key, value|
node[value] = row[key] unless row[key].nil?
end
#match urls
["Page Body Content", "Secondary Content"].each do |field|
matches = /(https?:\/\/[\'"]?[^\'" >]+)/.match(row[field])
matches.to_a.each do |match|
urls << match unless match.nil?
end
end
content << node
end
File.open("data.json", "w+") do |file|
file.write(content.to_json)
puts "Wrote #{file.path} - #{file.size}"
end
File.open("urls.json", "w+") do |file|
file.write(urls.to_json)
puts "Wrote #{file.path} - #{file.size}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment