将 CSV 中的 Json 哈希转换为 ruby 哈希
Convert Json hash in CSV to ruby hash
在 CSV 文件中,我有以下行:
data1;data2;{"key1":"value1","key2":"value2"}
我可以像这样解析它并得到我的 ruby 哈希:
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"}
在 CSV 文件中,我有以下行:
data1;data2;{"key1":"value1","key2":"value2"}
我可以像这样解析它并得到我的 ruby 哈希:
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"}