当前位置:网站首页>为什么要使用JSON.stringify()和JSON.parse()
为什么要使用JSON.stringify()和JSON.parse()
2022-07-25 09:20:00 【芳草斜阳_晨光】
前言
项目中经常会看到JSON.stringify()和JSON.parse()的使用,但是为什么会使用到它们?如何使用它们,本文将和你分享它们。
一、为什么要使用JSON.stringify()
JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串,数据在传输的过程中只能传输字符串。如果直接传输数据就会变成 [[Prototype]]: Object 无法使用了
二、JSON.stringify()是否使用情况对比
未使用时:
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'));

使用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'));

这时候返回后的值就不会是[[Prototype]]: Object 了,而是会有数据,但是和我们最初从后台获取的值还是会有不同,这时候就要用上JSON.parse() 了。
三、使用JSON.parse()进行解析数据
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')));

此时的数据就和后端返回的数据是一样的了,这样就可以在其它的组件页面中进行使用了
最后
如果分享对你有帮助记得点赞鼓励下哈!!!
边栏推荐
猜你喜欢

保姆级Scanner类使用详解
![[GYCTF2020]Node Game](/img/8d/7e6c2fb2a0359298fbcc1cd8544710.png)
[GYCTF2020]Node Game

A brief introduction to the interest of convolutional neural networks

Thick willow dustpan, thin willow bucket, who hates reptile man? Asynchronous synergism, half a second to strip away a novel

TCP网络应用程序开发流程

matplotlib数据可视化三分钟入门,半小时入魔?

Redis安装(Ubuntu)

数据查询语言(DQL)

Detailed explanation of the use of nanny scanner class

*6-1 CCF 2015-03-2 数字排序
随机推荐
Redis安装(Ubuntu)
~2 ccf 2022-03-1 未初始化警告
Notes on in-depth analysis of C language 1
Interviewer: tell me the difference between redis and mongodb? [easy to understand]
<T>泛型方法演示
@3-1 CCF 2020-09-1 称检测点查询
【代码源】每日一题 三段式
深入解读C语言随机数函数和如何实现随机数
C#语言和SQL Server数据库技术
What is the difference between mongodb and redis
OverTheWire-Bandit
The difference between abstract classes and interfaces (the most detailed)
[HCTF 2018]admin
jsPDF生成PDF文件,文件不全问题,后台进行文件下载,前台不下载
Go基础2
MySQL takes the query result as the data updated by update, and concatenates it after the original field data (Lej)
~4.2 ccf 2021-12-1 序列查询
『怎么用』观察者模式
卷积神经网络的兴趣简单介绍
~3 ccf 2022-03-2 出行计划