Skip to content

Instantly share code, notes, and snippets.

@Vchekryzhov
Created June 17, 2018 16:58
Show Gist options
  • Save Vchekryzhov/97df15a5df46c97ce057526084e3fc9d to your computer and use it in GitHub Desktop.
Save Vchekryzhov/97df15a5df46c97ce057526084e3fc9d to your computer and use it in GitHub Desktop.
Парсер ксв json
# Парсит электронную таблицу сохраненую в формате csv в json
# В первой строке должны быть записаны ключи
# run: ruby parser.tb filename.csv
# Пример
# -------------------
# Имя | Улица |дом|
# -------------------
# Андрей|Ленина |44 |
# Денис |Маркса |98 |
# ||
# ||
# \/
#[
# {"Имя":"Андрей","Улица":"Ленина","Дом":"44"},
# {"Имя":"Денис","Улица":"Маркса","Дом":"98"}
#]
require 'csv'
require 'json'
def csv_to_array(file_location)
csv = CSV::parse(File.open(file_location, 'r') {|f| f.read })
fields = csv.shift
fields = fields.map {|f| f.gsub(" ", "")}
csv.collect { |record| Hash[*fields.zip(record).flatten ] }
end
filename = ARGV[0]
hashes = csv_to_array('./'+filename)
File.open(filename+'_out'+'.json', 'w') do |f|
f.write("[\n")
hashes.each_with_index do |h,index|
f.write(h.to_json)
f.write(",\n") unless index == hashes.size - 1
end
f.write(']')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment