如何通过在rails上使用ruby来转换json中的文本文件

时间:2014-05-23 17:51:26

标签: jquery ruby-on-rails ruby json

我的文字文件test.txt包含2234#2#"Rama is god"#abcd#2(这是第1行的句子)

我需要将其转换为json 像这样

 snumber => 2234, 
 revision =>2
 msg => "rama is god" 
 se => "abcd"
 number =>2

1 个答案:

答案 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
# }