javascriptjsonweb-storage

JSON example confusing me - about JSON.parse, JSON.stringify, localStorage.setItem and localStorage.getItem


I'm just starting to learn JSON and W3schools isn't very good at explaining what each line does. I can sort of figure out what some of them mean, but I'd like to figure it out completely.

// Storing data:
1. myObj = {name: "John", age: 31, city: "New York"};
2. myJSON = JSON.stringify(myObj);
3. localStorage.setItem("testJSON", myJSON);

// Retrieving data:
4. text = localStorage.getItem("testJSON");
5. obj = JSON.parse(text);
6. document.getElementById("demo").innerHTML = obj.name;

So I know what line one is. It's just storing the variables. I'm going to assume line two is just turning the variable storage into a string. If that's incorrect please tell me. I have no idea what line three means, so can someone explain what that's doing?

line 4 and 5 confuse me as well. Line 6 is easy to understand.

TLDR: What are lines 2,3,4, and 5 doing?


Solution

  • I'll run through each line step by step.

    Saving

    1. myObj = {name: "John", age: 31, city: "New York"};
      • This line creates the object.
    2. myJSON = JSON.stringify(myObj);
      • This line turns the javascript object into a JSON string usable by any application that accepts JSON.
    3. localStorage.setItem("testJSON", myJSON);
      • Modern browsers have a localStorage API that allows you to store data in the browser. This line is storing that JSON string inside of localStorage for later use.

    Retrieving

    1. text = localStorage.getItem("testJSON");
      • This line is retrieving the stored JSON string.
    2. obj = JSON.parse(text);
      • This parses the retrieved JSON string back into a Javascript object.
    3. document.getElementById("demo").innerHTML = obj.name;
      • This will access the name property of the object that you parsed and print it to the demo element on the page.