Yosharu
Yosharu

Reputation: 33

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?

Upvotes: 3

Views: 2415

Answers (7)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

Window.localStorage

localStorage is part of Web Storage API, that allows you to store some data without expiration like sessionStorage. This is feature of almost all modern browsers, that allows you to store key/value pairs for the purpose of reusing them. It is meant to be kind of replacement for some usage of cookies

localStorage.getItem() and localStorage.setItem() are most common methods used, to retrieve data for given key, and set data value for given key.

Typical use for localStorage.setItem() is when you need to store some data for future use, so it won't be lost when user refreshes page, or opens other page. When you need to retrieve data you stored, you use localStorage.getItem().

Similar to localStorage, you have sessionStorage, that is similar. Only difference is that sessionStorage has expiration time, so it is best to use it when you don't want to temporary store some data.

Important: Keep in mind that storing data in this way is not secure, so avoid storing confidential data.

JSON.parse and JSON.stringify

JSON.parse is used to convert JSON string format into an object, and JSON.stringify is used to convert object into string.

Typical use for JSON.parse is when you get string from some external source, since string is the way to store the data. It converts string into an object, which can be used in your JavaScript code to manipulate with data properties from that object. JSON.stringify is mostly used to store data as a string, after you did some manipulation with properties from an object.

See more about Web Storage API:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

About JSON and JSON.stringify and JSON.parse methods:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

Upvotes: 0

Mat Waroff
Mat Waroff

Reputation: 56

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.

Upvotes: 4

Peter Collins
Peter Collins

Reputation: 37

First off, please note the tutorial you're referring to states in red text "You'll learn more about JSON.parse() / JSON.stringify() later in the tutorial.

In short, stringify() is a function to convert the json object into a string. parse() is a function that parses the string so an output can be produced from it.

Upvotes: 0

Willy David Jr
Willy David Jr

Reputation: 9131

Line one: Creates a variable object.

Line two: Converts the object to JSON.

Line three: Store the object on localstorage and sets its key value pair. Its key is named "testJSON"

Line four: Retrieves the localStorage using its key.

Line five: Parses the data and converts it to object.

Line six: Set the element id value on object with key "name".

Upvotes: 0

Hemant Parashar
Hemant Parashar

Reputation: 3774

Here is the explanation :

// Storing object with key name and city in a variable named myObj
1. myObj = {name: "John", age: 31, city: "New York"};

//Converting the myObj into a string representation called serializing/serialization
2. myJSON = JSON.stringify(myObj);

//Setting a key named testJSON in browsers localStorage
//coz You cannot store anything in localStorage except a string
3. localStorage.setItem("testJSON", myJSON);

// Retrieving data from the localStorage
4. text = localStorage.getItem("testJSON");

//Converting it back to object form from the string by parsing it
5. obj = JSON.parse(text);

//Setting the html of #demo element in dom to the name 
6. document.getElementById("demo").innerHTML = obj.name;

Upvotes: 2

GBrandt
GBrandt

Reputation: 685

So I know what line one is. It's just storing the variables

Yes.

I'm going to assume line two is just turning the variable storage into a string.

That's correct.

I have no idea what line three means

Refer to MDN localStorage documentation. This line has nothing to do with the JSON object itself, just shows you that you can save that object on localStorage and use it later when you load that page again, which btw is exactly what Line 4 does.

What Line 5 does is basically the reverse process for Line 2, so you give it a string with valid JSON and it returns a proper JS object.

Upvotes: 3

Serge K.
Serge K.

Reputation: 5323

  • Line 2 is serializing your object to a string in order to store it...
  • ... In the local storage which a sort of database (line 3).
  • Line 4 asks the local storage to return the previously stored value,
  • As it is serialized (you store it in string), you have to parse it ("convert it") to a JavaScript object in order to use it (using JSON.parse).

Upvotes: 0

Related Questions