Alex Crim
Alex Crim

Reputation: 57

Ruby: malformed CSV when converting to json

I'm trying to convert a csv file of incident codes with their descriptions to a json file. with the following code.

require 'csv'
require 'json'

csv = File.open('incidentCodes.json').read
CSV.parse(csv).to_json

File.open("incidentCodes.json", "w") do |f|
  f.write(csv)
end

Every time I run the code though it says "CSV::MalformedCSVError(Illegal quoting in line 1) "

This is the first few lines of my CSV

111, "Building fire. Excludes confined fires."
112, "Fire in structure, other than in a building. Included are fires on or in piers, quays, or pilings: tunnels or under-
ground connecting structures; bridges, trestles, or overhead elevated structures; transformers, power or utility
vaults or equipment; fences; and tents."
113, "Cooking fire involving the contents of a cooking vessel without fire extension beyond the vessel"
114, "Chimney or flue fire originating in and confined to a chimney or flue. Excludes fires that extend beyond the
chimney."

I tried bypassing using CSV.parse with other methods I saw but it was then only writing "[['incidentCodes.csv']]" to the json file. Im very new to ruby so any help is a big help.

Upvotes: 0

Views: 81

Answers (1)

Kamil Gwóźdź
Kamil Gwóźdź

Reputation: 774

You have an extra space after the comma.

> CSV.parse '111, "Building fire. Excludes confined fires."'
=> CSV::MalformedCSVError: Illegal quoting in line 1.

> CSV.parse '111,"Building fire. Excludes confined fires."'
=> [["111", "Building fire. Excludes confined fires."]]

Upvotes: 1

Related Questions