Skip to content

Instantly share code, notes, and snippets.

@tlewin
Created March 1, 2015 00:20
Show Gist options
  • Save tlewin/686b6ff5e90330a74aac to your computer and use it in GitHub Desktop.
Save tlewin/686b6ff5e90330a74aac to your computer and use it in GitHub Desktop.
Simple Ruby script to convert HAR files into CSV files
#! /usr/bin/env ruby
require 'oj'
require 'csv'
require 'uri'
unless ARGV.size == 2
puts 'USAGE:'
puts "\t har2csv.rb har_filename csv_filename"
exit 0
end
har_filename = ARGV.first
csv_filename = ARGV.last
har = Oj.load_file(har_filename, symbol_keys: true)
def mime2 mime
s = mime.split('/')
if s.first == 'image'
s.first
else
s.last
end
end
def max *values
values.map {|v| v || 0.0}.max
end
csv_string = CSV.generate do |csv|
# CSV header
csv << %w(
time
method
hostname
path
status
num_cookies
size
compression
downloaded
mimeType
mime2
t_blocked
t_dns
t_connect
t_send
t_wait
t_receive
t_ssl
)
# CSV body
har[:log][:entries].each do |entry|
uri = URI(entry[:request][:url])
csv << [
entry[:time],
entry[:request][:method],
uri.hostname,
uri.path,
entry[:response][:status],
entry[:response][:cookies].size,
size = entry[:response][:content][:size],
compression = entry[:response][:content][:compression] || 0,
max(size - compression, 0.0),
mime = entry[:response][:content][:mimeType],
mime2(mime),
max(entry[:timings][:blocked], 0.0),
max(entry[:timings][:dns], 0.0),
max(entry[:timings][:connect], 0.0),
max(entry[:timings][:send], 0.0),
max(entry[:timings][:wait], 0.0),
max(entry[:timings][:receive], 0.0),
max(entry[:timings][:ssl], 0.0)
]
end
end
File.write(csv_filename, csv_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment