Mahalingam Sundararaj
Mahalingam Sundararaj

Reputation: 77

I can't able to parse a localStorage sting into JSON object

let arr = {};
 
arr['0'] = '5';
arr['1'] = '4';
 
localStorage.setItem('arr', arr);
val = localStorage.getItem('arr');
console.log(val);

If I put val = JSON.parse(localStorage.getItem('arr'));, it throws an error stating that Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at app.js:230.

arr is an object, when I stored it to localStorage, it got stored as string of [object object], how can i access the individual value of arr from localStorage.

Upvotes: 0

Views: 1284

Answers (3)

Rohit Tagadiya
Rohit Tagadiya

Reputation: 3720

Try this..

let arr = {};

arr['0'] = '5';
arr['1'] = '4';

localStorage.setItem('arr', JSON.stringify(arr));

val = JSON.parse(localStorage.getItem('arr'));

console.log(val);

Upvotes: 0

bakar_dev
bakar_dev

Reputation: 996

Use this while storing:

localStorage.setItem("arr", JSON.stringify(arr));

while getting:

let val = JSON.parse(localStorage.getItem('arr'))

Upvotes: 2

Duc Nguyen
Duc Nguyen

Reputation: 855

localStorage can only store strings, so you need to JSON.stringify when setItem and JSON.parse when getItem.

Upvotes: 1

Related Questions