将CSV中的Json哈希转换为ruby哈希

问题描述 投票:0回答:1

在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'

任何想法如何处理?谢谢

json csv hash ruby-2.4
1个回答
0
投票

我发现了使用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"}
© www.soinside.com 2019 - 2024. All rights reserved.