-1

I have a text file say data.txt which contains content of format:

( {
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 = "";
}
)
Zubair
  • 5,833
  • 3
  • 27
  • 49

1 Answers1

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)

What I've done here is use two regex functions to break down your data into a Ruby object, then I've used the JSON library to dump the object to JSON.

Carson Crane
  • 1,197
  • 8
  • 15