Create JSON of one dimension Ruby
I want to have this:
开发者_JAVA百科["(GKA) GOROKA, GOROKA, PAPUA NEW GUINEA"]
instead of:
[ [ "(GKA)", "GOROKA", "GOROKA", "PAPUA NEW GUINEA" ] ]
I have this code so far:
@aeropuertos = ""
f = File.open("./public/aeropuertos/aeropuertos.cvs", "r")
f.each_line { |line|
fields = line.split(':')
if (fields[2] == "N/A")
@line = "(" << fields[1] << ")" << ",," << fields[3] << "," << fields[4]
else
@line = "(" << fields[1] << ")" << "," << fields[2] << "," << fields[3] << "," << fields[4]
end
@aeropuertos += @line << "\n"
}
return CSV.parse(@aeropuertos).to_json
What should I do?
@aeropuertos = ""
f = File.open("./public/aeropuertos/aeropuertos.cvs", "r")
f.each_line { |line|
fields = line.split(':')
if (fields[2] == "N/A")
@line = "(" << fields[1] << ")" << ",," << fields[3] << "," << fields[4]
else
@line = "(" << fields[1] << ")" << "," << fields[2] << "," << fields[3] << "," << fields[4]
end
@aeropuertos += @line << "\n"
}
res = []
CSV.parse(@aeropuertos).each do |c|
res << c.join(',')
end
return res.to_json
There's no need for the CSV parser. Just create the structure you want as you read each line. That is, instead of making a large string in @aeropuertos
and parsing it with a CSV parser, make @aeropuertos
an array, and add each @line
to the array.
So, instead of this:
@aeropuertos += @line << "\n"
Do this:
@aeropuertos << @line
But be sure to say this at the beginning:
@aeropuertos = []
精彩评论