Created
June 17, 2018 16:58
-
-
Save Vchekryzhov/97df15a5df46c97ce057526084e3fc9d to your computer and use it in GitHub Desktop.
Парсер ксв json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Парсит электронную таблицу сохраненую в формате 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