I need to store an array in sessionStorage and found this answer helpful: Storing Objects in HTML5 localStorage
Storing the array with sessionStorage.setItem('flavors', JSON.stringify(flavors))
and retrieving the string with JSON.parse(sessionStorage.getItem('flavors'))
works the first time. Then, testing this plain-JavaScript PWA with the back- and forward- buttons, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Depending on the elements of the array, the column number can vary.
I can avoid the error by using:
flavors = sessionStorage.getItem('flavors').split(",");
instead of JSON.parse()
. Along with the error, I can console log the string which looks okay:
chocolate,vanilla,strawberry
What could be causing the error?
In order to parse JSON, the string must represent a valid JSON, in you case this JSON.parse('["chocolate","vanilla","strawberry"]')
will work