我需要读取包含大量数据的CSV文件并将其转换为JSON对象。我编写了这段代码,但生成的JSON对象中有一些错误,并不符合我的期望。
def readFromFile(fileName)
jsonFile = File.open('some.json','w')
CSV.foreach(fileName,:headers => true, :header_converters => :symbol) do |row|
$jsonData['Email'] = {
:subject => row[0],
:body => row[1],
:fromName => row[2],
:fromEmail => row[3],
:toName => row[5],
:toEmail => row[6]
}
# puts "data is #{jsonData[jsonData.length-1]}"
jsonFile.write(JSON.pretty_generate($jsonData));
# CSV.parse(row).to_json
# @jsonFile.write(JSON.pretty_generate(@jsonData));
# csv = CSV.new(fileName, :headers => true, :header_converters => :symbol, :converters => :all)
# csv.to_a.map {|row| row.to_hash }
end
答案 0 :(得分:1)
我认为此代码可以帮助您(我从http://jasonheppler.org/2014/07/12/parsing-csv-to-json/获得):
def readFromFile(fileName)
def is_int(str)
# Check if a string should be an integer
return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
end
lines = CSV.open(filename).readlines
keys = lines.delete lines.first
File.open('some.json', "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
end