Remember that JSON has to be formatted before it can be saved and properly parsed when retrieved. These gotchas can hurt if you are working with JavaScript objects and are expecting them to be native objects from the start.
When saving JSON data to storage, make sure that you are calling the JSON.stringify()
method on your object either before or during the localStorage.setItem('key', value)
call. What this ensures is that the value will be a properly formatted JSON string and will retain its relationship data and values.
Upon retrieval of JSON in localStorage, make sure that you are calling JSON.parse()
on the localStorage.getItem('key')
call so that the data can be properly formatted back to a JavaScript object with proper keys and values.
I have provided some sample calls below to show how this can be done:
// JavaScript object to handle favorite games:
let favorites = [
{ id: 1, title: 'Jenga' },
{ id: 5, title: 'Tic-Tac-Toe' }
];
// Saving them into localStorage:
localStorage.setItem('favorites', JSON.stringify(favorites));
// the result will be this as a value in localStorage:
// [{"id":1,"title":"Jenga"},{"id":2,"title":"Tic-Tac-Toe"}]
// Get the data back from localStorage:
let retrievedFavorites = JSON.parse( localStorage.getItem('favorites') );
// The retrievedFavorites now has the object again and could be applied
// back to the favorites variable if desired.
Ah ah ah, you didn’t parse the JSON!
The idea behind this post is to show how to properly handle JSON data with localStorage so that you will not run into the same issues I had. I was constantly questioning my code wondering why it was not working properly. Ultimately, my issue was that I was not parsing the JSON values when I retrieved from the storage.