#!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'csv'
def is_int(str)
return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
end
lines = CSV.open(ARGV[0],{:col_sep => "\|"}).readlines
keys = lines.delete lines.first
File.open(ARGV[1], "w") do |f|
data = lines.map do |values|
is_int(values) ? values.to_i : values.to_s
Hash[keys.zip(values)]
end
f.puts JSON.pretty_generate(data)
end
I have this Ruby script for parsing a csv file and printing a second file in JSON format.
Im not really good with Ruby, but id like to modify it for
- read the csv file
- for any line (excepts the first that is a header)
- create a file.json where the name of the file is the second field of the line
For example:
the csv file:
ID|NAME|SURNAME|TELEPHONE
01|Jhon|Smith|123456
02|Steve|Brown|654321
the output of file jhon.json:
[
{
"ID": "01",
"NAME": "Jhon",
"SURNAME": "Smith",
"TELEPHONE": "123456",
},
]
Can someone help me?