JSON.parse()和JSON.stringify()

To find out the source, please go to https://www.sojson.com/json/json_stringify.html
JSON.parse and JSON.stringify are mutual conversions. There can be multiple parameters in the two methods. This article only shows one parameter, which is also commonly used in the development process.

JSON.parse(): Converts json string into json object

JSON.stringify(): Converts json objects into json strings

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字符串

Guess you like

Origin blog.csdn.net/weixin_42234899/article/details/129255937