user2085143 user2085143 - 4 months ago 12
JSON Question

JSON Parse from LocalStorage error

I am storing an object in localStorage using the following

function onExit(){
localStorage.setItem("my_object","'" + JSON.stringify(object) + "'");
}


When logging this out of localStorage it looks like this

'{"date":"2016-05-31T23:00:00.000Z","Name":"name","Code":"code","required":"false"}'


Now if I call JSON.parse on this directly it works, that is to say

JSON.parse('{"date":"2016-05-31T23:00:00.000Z","Name":"name","Code":"code","required":"false"}')


will give me an object. But if I try

JSON.parse(localStorage.my_object)


I get the 'unexpected character at line 1 of JSON data' error message

Where am I going wrong? Note: I have tried not enclosing the object in single quotes to no effect.

Answer

There is no need to wrap JSON.stringify(object) with the extra quotes ("'") as it returns a usable string.

localStorage.setItem("my_object",JSON.stringify(object));

To retrive and decode the JSON object, you need to call getItem

JSON.parse(localStorage.getItem("my_object"))