0

I am trying to save data from a Hash to a file. I convert it to JSON and dump it into the file. When I try to parse back from file to hash I get JSON::ParserError

Code to convert Hash to JSON file: (works fine)

user = {:email => "[email protected]", :passwrd => "hardPASSw0r|)"}

student_file = File.open("students.txt", "a+") do |f|
        f.write JSON.dump(user)
end 

After adding a few values one by one to the file it looks something like this:

{"email":"[email protected]","passwrd":"qwert123"}{"email":"[email protected]","passwrd":"qwert12345"}{"email":"[email protected]","passwrd":"hardPASSw0r|)"}

I tried the following code to convert back to Hash but it doesn't work:

file = File.read('students.txt')
data_hash = JSON.parse(file)

I get

System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/json/common.rb:155:in `parse': 757: unexpected token at '{"email":"[email protected]","passwrd":"qwert12345"}{"email":"[email protected]","passwrd":"hardPASSw0r|)"}' (JSON::ParserError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/json/common.rb:155:in `parse'
    from hash_json.rb:25:in `<main>'

My goal is to be able to add and remove values from the file. How do I fix this, where was my mistake? Thank you.

2
  • 1
    you are write file with a+ so you append one json object to another. is it what you need? can't you write without append? Commented Nov 14, 2016 at 9:07
  • @Aleksey I don't have to use +a no. How does the solution go in that case? Commented Nov 14, 2016 at 9:14

1 Answer 1

1

This should work:

https://repl.it/EXGl/0

# as adviced by @EricDuminil, on some envs you need to include 'json' too
require 'json'

user = {:email => "[email protected]", :passwrd => "hardPASSw0r|)"}

student_file = File.open("students.txt", "w") do |f|
  f.write(user.to_json)
end 

file = File.read('students.txt')

puts "saved content is: #{JSON.parse(file)}"

p.s. hope that this is only an example, never store passwords in plain-text! NEVER ;-)

Sign up to request clarification or add additional context in comments.

2 Comments

Yes. Depending on your environment, you might want to require 'json' first.
correct @EricDuminil - I will add your suggestion to my code-snippet. Thanks.

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.