Uday kumar das Uday kumar das - 5 months ago 12
Ruby Question

read all contents of a txt file and parse it to JSON format

In

demo.txt
file:

'{
"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4}
]
}
}'


Expected result:

{
"cars" => {
"Nissan" => [
{
"model"=>"Sentra",
"doors"=>4
},
{
"model" => "Maxima",
"doors"=>4
}
]
}
}


I want to read whole content of the file and parse it to JSON format like
JSON.parse(file_contents)
.Help me out.

I have tried like:

file_contents = File.readlines 'demo.txt'
arr = []
file_contents.each do |d|
puts arr << d.gsub("\n","")
end
puts arr # ["'{", "\"cars\": {", "\"Nissan\": [", "{\"model\":\"Sentra\", \"doors\":4},", "{\"model\":\"Maxima\", \"doors\":4}", "]", "}", "}'"]

puts arr * '' #"'{\"cars\": {\"Nissan\": [{\"model\":\"Sentra\", \"doors\":4},{\"model\":\"Maxima\", \"doors\":4}]}}'"

Answer

If you can strip out the leading and trailing ' with gsub or something else, it's as simple as

require 'JSON'
JSON.parse(File.open('demo.txt').read.chop!.reverse.chop!.reverse)