【问题标题】:Ruby: malformed CSV when converting to jsonRuby:转换为 json 时格式错误的 CSV
【发布时间】:2020-05-11 15:56:18
【问题描述】:

我正在尝试将事件代码及其描述的 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​​ 很陌生,所以任何帮助都是很大的帮助。

【问题讨论】:

    标签: json ruby csv


    【解决方案1】:

    逗号后面多了一个空格。

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

    【讨论】:

    • 是的,做到了。谢谢!
    猜你喜欢
    • 2015-02-26
    • 2015-03-26
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多