Reputation: 323
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.
Upvotes: 0
Views: 178
Reputation: 6238
This should work:
# 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 ;-)
Upvotes: 1