About JSON.stringify () and JSON.parse ()

First, the difference JSON.stringify () and JSON.parse () of

  Effect of the JSON.stringify () is converted into a value js JSON string, while the JSON.parse () is converted into a JSON string object. That is, if we use JSON.stringify () an object into a string, use JSON.parse () to restore the string into an object.

let obj = {
name:"song",
age:10
};
let changeObj =JSON.stringify(obj);
console.log(changeObj); //"{"name":"song","age":10}"
console.log(typeof changeObj);//string

let orig =JSON.parse(changeObj);
console.log(orig);//{name:"song",age:10}
console.log(typeof orig);//object

    

Two, JSON.stringify () and JSON.parse () several usage

(A) objects stored in localStorage / sessionStorage li / array / array of objects

     localStorage / sessionStorage default string stored only, if you want to store the object data type, when deposited using the JSON.stringify () to convert an object into a string, and then taken out at the time of using the JSON.parse () transfected We will be back to the object.

1  // save data 
2 localStorage.setItem ( "Cart" , the JSON.stringify (n-));
 . 3  
. 4  // fetch 
. 5 the JSON.parse (window.localStorage.getItem ( "Cart"));

(B) routing parameter passing VUE (object)

   Sometimes, if the object inside just one or two attributes, you can directly use literal way to define the object, but if the object needs to be passed has a lot of attributes, then write a one is obviously undesirable. So you can use to convert JSON.stringify () and JSON.parse ().

1 this.$router.push({ 
2     name: "DataDetail", 
3     query: {    
4         tabsVal: JSON.stringify(val),  
5         Name: this.$route.query.name 
6         }
7 });​

Deep copy (C) to achieve the object / array

   In fact, this data is directly converted into a string and then copied back after completion of the conversion, actually a very good solution.

 

var obj2 = {
    name:"L",
    age:12,
    value:"IU"
}
obj1=JSON.parse(JSON.stringify(obj2));

If (D) determines the array / objects are equal, or if a certain content is determined

  Used to determine whether the array / objects are equal in this way really easy, both to be compared are first translated into strings and can be determined directly congruent.

Guess you like

Origin www.cnblogs.com/songForU/p/11685258.html