我的文字文件test.txt
包含2234#2#"Rama is god"#abcd#2
(这是第1行的句子)
我需要将其转换为json
像这样
snumber => 2234,
revision =>2
msg => "rama is god"
se => "abcd"
number =>2
答案 0 :(得分:0)
您可以使用split
来解析该行,从中创建一个哈希值,您可以将其转换为JSON;
require 'json'
text = IO.read('test.txt')
snumber, revision, msg, se, number = text.split('#')
# => ["2234", "2", "\"Rama is god\"", "abcd", "2"]
target_hash = {snumber: snumber.to_i, revision: revision.to_i , msg: msg.downcase[1..-2], se: se, number: number.to_i }
# => {:snumber=>2234, :revision=>2, :msg=>"rama is god", :se=>"abcd", :number=>2}
puts JSON.pretty_generate target_hash
# {
# "snumber": 2234,
# "revision": 2,
# "msg": "rama is god",
# "se": "abcd",
# "number": 2
# }