0

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.

1
  • works for me... are you certain you don't have a typo? Commented Jul 26, 2016 at 15:58

2 Answers 2

4

Either, save your object without quotes i.e.

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

Or, if you do not remove quotes while saving, then you need to remove the enclosing quotes before trying to parse the object.

Sign up to request clarification or add additional context in comments.

Comments

2

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"))

1 Comment

Yes, I was missing getItem cheers. Will accept when it lets me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.