1

I am a novice in JavaScript and I just need some help for a project that requires JavaScript. I need to store Json objects in the browser.

How would I store a Json object in local storage of a browser?

Also, how would I retrieve it?

Here is what I have right now:

//Json object
var obj{
   "name":"Quandale Dingle",
   "age":24,
   "team":"Seahawks"
}

//Storing it in local storage
localStorage.setItem(obj);

I checked my console for the getItem, and I would not get any result.

Rodger
  • 33
  • 4
  • That's not a "json object". That's just a javascript object. As for how you use localStorage: it stores strings. So you turn your data into a string, save it, and parse it when you need to load it. – Mike 'Pomax' Kamermans Dec 16 '22 at 05:29
  • 1
    You should Stringify obj by: JSON.stringify(obj) and then add it to local storage using with an associated key. – Rohan Singh Dec 16 '22 at 05:40
  • 1
    To fetch it you would have to use: localStorage.getItem() and then parse it into a Json object using JSON.parse(jsonString). – Rohan Singh Dec 16 '22 at 05:42
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – Andy Dec 16 '22 at 05:45

1 Answers1

0
var obj = {
   "name":"Quandale Dingle",
   "age":24,
   "team":"Seahawks"
}

Set

localStorage.setItem('foo', JSON.stringify(obj))

Get

JSON.parse(localStorage.getItem('foo'))

// {name: 'Quandale Dingle', age: 24, team: 'Seahawks'}
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62