0

I have two js files. In one file, I am creating an array of objects and storing them in local storage. In another file, I am retrieving highscores_list from localStorage.

I get an error at this line stating:

VM2055:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1'

File 1

var highscores_list = [
    {name:'sham' , score: 10},
    {name:'John' , score: 9}
];

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

File 2

var getListItems = JSON.parse(localStorage.getItem('highscores_list')); 
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting) – Andreas Jun 20 '20 at 17:14
  • [The error doesn't match the code you've shown](https://stackoverflow.com/questions/38380462/syntaxerror-unexpected-token-o-in-json-at-position-1). Either `localStorage.getItem('highscores_list')` returns the string `"[object Object]"` or it returns an actual object ([which is not possible](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem)). – Andreas Jun 20 '20 at 17:21

2 Answers2

0

The error clearly says that there is some problem with your JSON at some point. So it is either during JSON.parse() or JSON.stringify. Do one thing, try to validate your JSON in some online JSON linting tool and see if it is valid. The example given in the question should work right. In case you are using some different JSON could you please share the fiddle maybe.

Pushkar Kathuria
  • 331
  • 2
  • 17
0

You have to use stringify twice on the object that you are storing in local storage.

var highscores_list = [
    {name:'sham' , score: 10},
    {name:'John' , score: 9}
];

highscores_list = JSON.stringify(highscores_list);

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