2015-10-16 57 views
0

我有一個文本文件說data.txt中包含格式的內容:轉換文本到JSON

({ 
city = Leesburg; 
country = USA; 
dob = ""; 
email = "[email protected]"; 
firstName = "EricM."; 
homePhone = ""; 
lastName = Abcdef; 
mobilePhone = 12312312; 
state = Virginia; 
workPhone = 12312312; 
}, 
{ 
city = "Mt. Uncle"; 
dob = ""; 
email = ""; 
firstName = first; 
homePhone = ""; 
lastName = Berry; 
mobilePhone = 234234; 
state = MD; 
workPhone = ""; 
} 
) 
+0

你想用這個文件做什麼?你想用Ruby解析它嗎?你想手動編輯它成爲JSON嗎?這個文件來自哪裏? –

+0

最簡單的事情就是我擁有它,而且我需要從中創建一個有效的JSON。 – Zubair

+0

如果你只需要從這個文件中創建JSON而沒有其他文件,那麼最簡單的就是手動完成! – sourcx

回答

0
require "json" 

file = File.open("data.txt") 

contents = file.read 

hashes = contents.scan(/{(.*?)}/mx) 

arr = [] 
hashes.each do |hash| 
    hashitems = hash[0].scan(/(\w+\s=\s.+?);/) 
    ahash = {} 
    hashitems.each do |hashitem| 
     itemarr = hashitem[0].split(" = ") 
     ahash[itemarr[0]] = itemarr[1] 
    end 
    arr << ahash 
end 

print JSON.dump(arr) 

我在這裏所做的是使用兩個正則表達式的功能將數據分解成一個Ruby對象,然後我使用JSON庫將對象轉儲爲JSON。