我有一个文本文件说data.txt,其中包含格式的内容:
( {
city = Leesburg;
country = USA;
dob = "";
email = "email@domain.com";
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 :(得分: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。