Airwavezx Airwavezx - 1 year ago 130
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

it into the file.
When I try to parse back from file to hash I get

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

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

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

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


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

file ='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":"","passwrd":"qwert12345"}{"email":"","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 Source

This should work:

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

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

student_file ="students.txt", "w") do |f|

file ='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 ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download