Skip to content

Instantly share code, notes, and snippets.

@shunwen
Created September 9, 2013 08:18
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 shunwen/6492832 to your computer and use it in GitHub Desktop.
Save shunwen/6492832 to your computer and use it in GitHub Desktop.
Replace Rails log with json format, then convert each json entries from the log file to csv.
require 'json'
require 'csv'
SAMPLE_DATA = {"key1": "value1", "key2": "value2", "key3": "value3"}
headers = JSON.parse(SAMPLE_DATA).keys
input_lines = File.readlines "path/to/log/file"
parsed_line = 0
csv_file = CSV.open "path/to/file.csv", "w"
csv_file << headers
input_lines.each do |line|
begin
record = JSON.parse line
csv_file << headers.map {|h| record[h]}
parsed_line += 1
rescue
end
end
puts "TOTAL LINES: #{input_lines.length}"
puts "PARSED LINES: #{parsed_line}"
puts "UNPARSED LINES: #{input_lines.length - parsed_line}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment