在CSV文件中,我有以下一行:
data1;data2;{"key1":"value1","key2":"value2"}
我可以解析它并得到我的红宝石哈希:
require 'csv'
line = 'data1;data2;{"key1":"value1","key2":"value2"}'
csv = CSV.parse_line(line, col_sep: ";", quote_char: "\x00")
=> ["data1", "data2", "{\"key1\":\"val", "ue1\",\"key2\":\"value2\"}"]
JSON.parse(csv[2])
但是,当值包含分隔符(;
)时,它会失败,因为它会被解释
require 'csv'
line = 'data1;data2;{"key1":"val;ue1","key2":"value2"}'
csv = CSV.parse_line(line, col_sep: ";", quote_char: "\x00")
=> ["data1", "data2", "{\"key1\":\"val", "ue1\",\"key2\":\"value2\"}"]
# Of course
JSON.parse(csv[2])
JSON::ParserError: 784: unexpected token at '{"key1":"val'
任何想法如何处理?谢谢
我发现了使用CSV写入哈希的正确语法。从[]更改csv文件中的哈希
data1;data2;{"key1":"val;ue1","key2":"value2"}
到
data1;data2;"{""key1"":""val;ue1"",""key2"":""value2""}"
这不是真正的人类可读的,但是有效。
完整的工作代码:
require 'csv'
line = 'data1;data2;"{""key1"":""val;ue1"",""key2"":""value2""}"'
csv = CSV.parse_line(line, col_sep: ";", quote_char: "\"")
=> ["data1", "data2", "{\"key1\":\"val;ue1\",\"key2\":\"value2\"}"]
JSON.parse(csv[2])
=> {"key1"=>"val;ue1", "key2"=>"value2"}