JSON.parse()和JSON.stringify()

想搞清楚来源,请移步https://www.sojson.com/json/json_stringify.html
JSON.parse和JSON.stringify是相互转化,两个方法中可有多个参数,此文仅展示一个参数,也是平时开发过程中比较常用的

JSON.parse(): 是将json字符串转化为json对象

JSON.stringify():是将json对象转化为json字符串

console.log(localStorage.getItem('userInfo')) // 得到的是JSON字符串
console.log(localStorage.getItem('userInfo').userName) // JSON字符串是string类型,所以不存在key-value,因此报undefined
console.log(JSON.parse(localStorage.getItem('userInfo'))) // JSON.parse将JSON字符串转化为JSON对象
console.log(JSON.parse(localStorage.getItem('userInfo')).userName) // 对象存在key-value值
console.log(JSON.stringify(JSON.parse(localStorage.getItem('userInfo')))) // JSON.stringify是将json对象转化为JSON字符串

猜你喜欢

转载自blog.csdn.net/weixin_42234899/article/details/129255937