I have a working method that opens and parses a json file. Now I'm trying to iterate through a directory of json files and display their contents.
Working method for a single file:
def aperson
File.open("people/Elvis Presley.json") do |f|
parse = JSON.parse(f.read)
end
end
Non-working method to iterate through a directory:
16. def list
17. Dir.glob('people/*').each do |f|
18. parse = JSON.parse(f)
19 end
20. end
My error is:
/Users/ad/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/json/common.rb:148:in `parse': 743: unexpected token at 'people/Elvis Presley.json' (JSON::ParserError)
from /Users/ad/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/json/common.rb:148:in `parse'
from app.rb:18:in `block in list'
from app.rb:17:in `each'
from app.rb:17:in `list'
from app.rb:24:in `<main>'
All of the files in the directory have the same content and are valis as per JSONlint.
Any help would be greatly appreciated.
You tried to parse the filename as JSON, which won't work.
Instead, you need to read the file first:
parse = JSON.parse(File.read(f))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With