最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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 pletely.

// 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?

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 pletely.

// 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?

Share Improve this question edited Mar 8, 2019 at 17:24 Nikola Kirincic 3,7571 gold badge27 silver badges32 bronze badges asked Mar 8, 2019 at 16:53 YosharuYosharu 331 silver badge6 bronze badges 3
  • 5 MDN is a much better source for learning: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Davide Vitali Commented Mar 8, 2019 at 16:57
  • 4 Agree with Davide - Check out MDN - developer.mozilla/en-US/docs/Web/API/Window/localStorage, developer.mozilla/en-US/docs/Web/JavaScript/Reference/…, developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – DaveStSomeWhere Commented Mar 8, 2019 at 16:59
  • You can even refer w3schools./html/html5_webstorage.asp – Subhendu Kundu Commented Mar 8, 2019 at 17:00
Add a ment  | 

7 Answers 7

Reset to default 4

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.

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.

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;
  • 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).

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".

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.

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 mon 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/en-US/docs/Web/API/Web_Storage_API

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

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论