首页 > 解决方案 > Ruby:转换为 json 时格式错误的 CSV

问题描述

我正在尝试将事件代码的 csv 文件及其描述转换为 json 文件。使用以下代码。

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

每次我运行代码时都会显示“CSV::MalformedCSVError(Illegal quoting in line 1)”

这是我的 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."

我尝试使用 CSV.parse 绕过我看到的其他方法,但它只是将“[['incidentCodes.csv']]”写入 json 文件。我对 ruby​​ 很陌生,所以任何帮助都是很大的帮助。

标签: jsonrubycsv

解决方案


逗号后有一个额外的空格。

> 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."]]

推荐阅读