0

我正在尝试解析一些包含随机 JSON 的 CSV。JSON 有双引号:

csv = CSV.parse('example,json=[{"json": "obj"}],endexample')
CSV::MalformedCSVError: Illegal quoting in line 1.
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1925:in `block (2 levels) in shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1887:in `each'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1887:in `block in shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1849:in `loop'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1849:in `shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1791:in `each'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1805:in `to_a'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1805:in `read'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1379:in `parse'
  from (irb):13
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>'

我已经读到在 CSV 中你在引号中转义了一个引号,所以我尝试了类似的东西.gsub('"','""'),但这并没有帮助。

csv = CSV.parse('example,json=[{""json"": ""obj""}],endexample')
CSV::MalformedCSVError: Illegal quoting in line 1.
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1925:in `block (2 levels) in shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1887:in `each'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1887:in `block in shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1849:in `loop'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1849:in `shift'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1791:in `each'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1805:in `to_a'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1805:in `read'
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1379:in `parse'
  from (irb):17
  from /Users/kevzettler/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>' 
4

1 回答 1

4

来自关于 CSV 的维基百科:

  • 应引用包含换行符、双引号和/或逗号的字段。(如果不是,则文件可能无法正确处理)。
  • 字段中的(双)引号字符必须由两个(双)引号字符表示。

尝试这个:

csv = CSV.parse('example,"json=[{""json"": ""obj""}]",endexample')
于 2013-06-12T22:12:40.500 回答