当前位置:网站首页>为什么要使用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')));

此时的数据就和后端返回的数据是一样的了,这样就可以在其它的组件页面中进行使用了
最后
如果分享对你有帮助记得点赞鼓励下哈!!!
边栏推荐
- office文件对应的Content-Type类型
- Jspdf generates PDF files. There is a problem of incomplete files. Files are downloaded in the background, but not in the foreground
- matplotlib数据可视化三分钟入门,半小时入魔?
- How can technologists start their personal brand? Exclusive teaching of top five KOLs
- Mongodb installation and use
- 【代码源】每日一题 农田划分
- 粗柳簸箕细柳斗,谁嫌爬虫男人丑 之 异步协程半秒扒光一本小说
- Week summary
- TCP网络应用程序开发流程
- Analysis of concat and group in MySQL_ Use of concat
猜你喜欢
随机推荐
数据库操作语言(DML)
Interviewer: tell me the difference between redis and mongodb? [easy to understand]
yarn : 无法加载文件 yarn.ps1,因为在此系统上禁止运行脚本。
SSM框架整合,简单案例
什么是单机、集群与分布式?
idea 热部署
uni-app如何获取位置信息(经纬度)
Redis安装(Ubuntu)
Numpy - 数组array的构造
sqli-labs Basic Challenges Less11-22
[De1CTF 2019]SSRF Me
Detailed explanation of pipeline pipeline mechanism in redis
Go基础3
Publish Yum private server using nexus3 (offline intranet)
Numpy- array属性、改变形状函数、基本运算
深入理解static关键字
【代码源】每日一题 算的我头都大啦
SSM高级整合
『每日一问』volatile干嘛的
最短路问题 Bellman-Ford(单源最短路径)(图解)
![[GYCTF2020]Ez_Express](/img/ce/02b90708f215715bb53cacfd4c21f0.png)



![[HCTF 2018]admin](/img/d7/f0155c72d3fbddf0a8c1796a179a0f.png)




