4

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.

3 Answers 3

9

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but instead of getting the content of each file I get a listing of the files: people/Anthony DeFreitas.json people/Elvis Presley.json people/Seth Godin.json people/Steve McQueen.json
Well, you need to do something with the result of parse. Otherwise, you're just going to get the result from Dir.glob (which is the list of filenames). Maybe you wanted to append the parsed data to a list?
Thanks, I guess I wrote the code wrong as I wanted to display the contents of each file and not just the file names. Thanks for your help nneonneo.
4

not sure, but can you try to parse the content of file instead of file name:

parse = JSON.parse( File.read f )

3 Comments

"people/#{f}" won't exist; f already contains the expanded filename. But yeah, he's trying to read a filename and not the file contents.
Your revised solution is identical to the code that doesn't work.
My goal is to read the contents of each file, sorry for not making that clear.
1

In your non-working code, f is just string of the expanded file name. So you need to read the file after you've received the filename in the block.

While writing it, @nneonneo already gave you solution. So I'm not giving again.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.