Why use JSON.stringify() and JSON.parse()


foreword

We often see the use of JSON.stringify() and JSON.parse() in projects, but why are they used? How to use them, this article will share them with you.


1. Why use JSON.stringify()

The JSON.stringify() method converts a JavaScript object or value into a JSON string, and only strings can be transmitted during data transmission. If the data is transferred directly, it will become [[Prototype]]: Object cannot be used

2. Comparison of whether JSON.stringify() is used or not

When not in use:

let abc = res.data.data.pages; //res是后端接口返回的数据,因为想要更好的说明情况在此处做了省略处理
console.log('后端返回的数据_abc:', abc);
sessionStorage.setItem('abc', abc);
sessionStorage.getItem('abc');
console.log('无JSON.stringify()_abc:', sessionStorage.getItem('abc'));

insert image description here
After using JSON.stringify():

let abc = res.data.data.pages; //res是后端接口返回的数据,因为想要更好的说明情况在此处做了省略处理
let def = JSON.stringify(res.data.data.pages);
console.log('后端返回的数据_abc:', abc);
sessionStorage.setItem('def', def);
sessionStorage.getItem('def');
console.log('有JSON.stringify()_def:', sessionStorage.getItem('def'));

insert image description here
At this time, the returned value will not be [[Prototype]]: Object, but will have data, but it will still be different from the value we originally obtained from the background. At this time, JSON.parse() must be used up.

3. Use JSON.parse() to parse data

let abc = res.data.data.pages; //res是后端接口返回的数据,因为想要更好的说明情况在此处做了省略处理
let def = JSON.stringify(res.data.data.pages);
console.log('后端返回的数据_abc:', abc);
sessionStorage.setItem('def', def);
sessionStorage.getItem('def');
//console.log('有JSON.stringify()_def:', sessionStorage.getItem('def'));
console.log('解析后的JSON.stringify()_def:', JSON.parse(sessionStorage.getItem('def')));

insert image description here
The data at this time is the same as the data returned by the backend, so that it can be used in other component pages

at last

If sharing is helpful to you, remember to like and encourage it! ! !

Guess you like

Origin blog.csdn.net/daishu_shu/article/details/124383384