Last Updated: February 23, 2018
·
3.923K
· jkcpr

Ruby parsing JSON from txt file.

require 'json'

badges = File.open("badges.txt", "r")

doc = ""
badges.each do |line|
  doc << line
end
badges.close

puts JSON.parse(doc)

JSON data for badges.txt

{ 
"badges" : 
  {
    "badge1" : {
      "name"  :  "Name of Badge1",
      "subject"  :  "Subject of Badge1 "
    },
    "badge2" : {
      "name"  :  "Name of Badge2",
      "subject"  :  "Subject of Badge2 "
    }
  }
} 

1 Response
Add your response

One-line alternatives:

JSON.parse File.read("badges.txt")
File.open "badges.txt", &JSON.method(:load)

over 1 year ago ·