简体   繁体   English

通过smartercsv gem导入CSV错误

[英]Csv import error through smartercsv gem

I have this csv structure 我有这个CSV结构

"CATEGORY";"NAME";"AGE"
"Red";"John";"34"

When I import the file through smarter_csv gem I get this hash 通过smarter_csv gem导入文件时,出现此哈希

{:"\"CATEGORY\""=>"\"Red\"", :"\"NAME\""=>"\"John\"", :"\"AGE\""=>"\"34\""}

The code I use is the following 我使用的代码如下

options = {:col_sep => ";",:row_sep => :auto, :quote_char => "\x00"}
SmarterCSV.process(save_folder, options) do |array|
    Item.create(array.first)
end

What puzzles me is the \\" that is added in each item of the hash. I have used this same method before without issues and I don't understand what is going wrong, but the expected hash should be plan text with no backslash and additional quotes. As a note, is I don't use the ";quote_char => "\\x00"" option I get a malformed csv error. 令我感到困惑的是在哈希的每个项目中添加的\\“。我以前使用过这种相同的方法,没有出现问题,我也不知道出了什么问题,但是预期的哈希应该是没有反斜杠和其他符号的计划文本注意,如果我不使用“; quote_char =>” \\ x00“”选项,则会收到格式错误的csv错误。

This works out of the box, but the quote_char you chose was incorrect; 开箱即用,但您选择的quote_char不正确; it should be '"' , which is the default setting. 它应该是'"' ,这是默认设置。

      require 'smarter_csv'
      SmarterCSV::VERSION
       => "1.2.3"

      data = SmarterCSV.process('/tmp/test.csv', {:col_sep => ";"})
       => [{:category=>"Red", :name=>"John", :age=>34}]

      # or like this:

      data = SmarterCSV.process('/tmp/test.csv', {
         :col_sep => ";",:row_sep => :auto, :quote_char => '"'
      })
       => [{:category=>"Red", :name=>"John", :age=>34}]          

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM