Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby json parse error: unexpected token

Tags:

json

ruby

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.

like image 748
Anthony Avatar asked Dec 08 '22 20:12

Anthony


1 Answers

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))
like image 82
nneonneo Avatar answered Dec 23 '22 01:12

nneonneo