I am attempting to write a program that takes user input and write it to a JSON file to be read later. Before doing so, I take the users input and create a hash and convert it to JSON format before writing it to a file. My problem arises when I have more than one JSON object that needs to be read from the file.
Here is my current code to create a hash and move data into a file and the method I use to read from the file.
#create hash of user input
tempHash = {
:first_name => $user_fname,
:last_name => $user_lname,
:raw_date => input_date,
:birthday => $user_bday
}
#open birthday_output.json file and write the JSON object to file
File.open("#{@filePath}/birthday_output.json", 'a+') do |file|
file.puts JSON.pretty_generate(tempHash)
file.close
end
#read the JSON object from file and return value of specific key
def file_reader(key)
file = File.read("#{@filePath}/birthday_output.json")
data_hash = JSON.parse(file)
return data_hash[key]
end
This all works great when I have only 1 JSON object in the file that I am attempting to read, but when I create another JSON object and write it to the file, I get the error listed below when attempting to parse the file. My goal is to create a file with user input and then read over those keys/values to see if the user input already exists in the file.
The error that I am recieving is
"in 'parse': 776: Unexpected token at ' JSON Parser error
"first_name": "Jon"
"last_name": "Stewart"
"raw_date": "2016-06-11"
"birthday": "June 11 2016"
My file looks like this when I get the error:
{
"first_name": "Hank",
"last_name": "Hill",
"raw_date": "2016-01-05",
"birthday": "January 05 2016"
}
{
"first_name": "Jon",
"last_name": "Stewart",
"raw_date": "2016-06-11",
"birthday": "June 11 2016"
}
Again, when only the Hank Hill JSON object exists in the file, I am able to call my file_reader method with the key that I am interested in and it outputs correctly. When I introduce the second JSON object to the file "Jon Stewart", it launches the error at me. Does anyone have any experience is what I am trying to do?