Airwavezx Airwavezx - 24 days ago 13
JSON Question

JSON to Hash in Ruby and vice-versa using Files - Parser Error

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 => "cumber@cc.cc", :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":"test1@gmail.com","passwrd":"qwert123"}{"email":"test3@gmail.com","passwrd":"qwert12345"}{"email":"cumber@cc.cc","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":"test3@gmail.com","passwrd":"qwert12345"}{"email":"cumber@cc.cc","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.

Answer

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 => "cumber@cc.cc", :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 ;-)