Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# To use, put this file, jay.rb, in a directory with the csv files you need to convert.
# Then just run the following command from the prompt:
# ruby jay.rb [name of file without the .csv]
# Get the libraries you need
require 'csv'
require 'json'
# ARGV[0] gets the name of the first argument you passed from the command line - in this case, the name of the csv file
input_file_name = ARGV[0] + '.csv'
output_file_name = ARGV[0] + '.json'
# Open the files. W+ gives write permission and creates the file if necessary
output_file =, "w+")
# Read the input file (the CSV file)
input_file =, "r")
# Create an empty array to put the resulting hashes in
entry_array = []
# Iterate over each entry in the CSV file (shift removes the first entry in the array, which is your headers)
JSON.parse(CSV.parse(input_file).to_json).shift.each do |entry|
# Create a new hash to store the values from the a given CSV array entry and assign the values
c =
c['Station'] = entry[0]
c['Time'] = entry[1]
c['TransactionNumber'] = entry[2]
c['UPC'] = entry[3]
c['Product'] = entry[4]
c['Dept'] = entry[5]
c['Cashier'] = entry[6]
c['SalesQty'], = entry[7]
c['Unit'] = entry[8]
c['Amount'] = entry[9]
c['Tax'] = entry[10]
# add the resulting hashes to the array of hashes
entry_array << c
# Write the array of hashes to a json file with the same name as the input file, except with the .json extension
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.