在JSON对象和JS对象相互转换的时候就会用到JSON.parse()和JSON.stringify()。在使用过程,也常常会碰到下面这三个问题:
- ReferenceError: JOSN is not defined
- Uncaught SyntaxError: Unexpected token a in JSON at position 1
- 打印JSON对象最外层没显示引号
1、围绕这三个问题,我们先来看看代码:
JSON对象
let jsonObj = '{"name":"xiaohong","age":16}'
console.log(jsonObj) // {"name":"xiaohong","age":16}
let jsonObjStr = JSON.stringify(jsonObj)
console.log(jsonObjStr) // "{\"name\":\"xiaohong\",\"age\":16}"
console.log(JSON.parse(jsonObjStr)) // {"name":"xiaohong","age":16}
console.log(JSON.parse(jsonObj)) // {name: 'xiaohong', age: 16}
JS对象
let obj = { name: 'xiaoming', age: 18 }
console.log(obj) // {name: 'xiaoming', age: 18}
let objStr = JSON.stringify(obj)
console.log(objStr) // {"name":"xiaoming","age":18} (其实外层是'{}')
console.log(JSON.parse(objStr)) // Uncaught SyntaxError: Unexpected token o in JSON at position 1
console.log(JSON.parse(obj)) // Uncaught SyntaxError: Unexpected token o in JSON at position 1
2、看完上面的代码,或许有了些启发:
ReferenceError: JOSN is not defined
这个报错的原因大概率是JSON.parse()&JSON.stringify()中的JSON写错了,可能写成JOSN了。
Uncaught SyntaxError: Unexpected token a in JSON at position 1
这个报错的原因是使用不合法的JSON对象(或非JSON对象)的字符串(或非字符串JSON对象)去JSON.parse()了。
那什么是JSON对象?
JSON对象也称JS对象表示法。用来作为数据交换的文本格式,作用类似于XML,不是一种编程语法,而是用来描述数据结构。在后端接口返回JSON对象这样的数据就会采用JSON.parse()来转为JS对象,来供页面渲染。
那什么是合法的JSON对象?
- 所有的属性名都必须用双引号包起来
- 所有的属性值为字符串都必须用双引号包起来
- 数组或对象的最后一个成员,不能加逗号
那什么是合法的JSON对象字符串?
- JSON对象外层用单引号包起来
// 例如:
let jsonObj = '{"name":"xiaohong","age":16}'
打印JSON对象最外层没显示引号
let jsonObj = '{"name":"xiaohong","age":16}'
let jsonObj = '{"name":"xiaozhang","age":28}'
console.log(jsonObj) // {"name":"xiaozhang","age":28} (注:JSON对象打印少了最外层引号)
3、JSON.parse()&JSON.stringify()
- JSON.parse()用于将一个JSON对象的字符串解析成一个JS对象
- JSON.stringify()用于将一个(JSON/JS)对象解析成一个字符串
一些场景
比如,有个页面的url后面拼接了参数跳转到详情页,为了防止详情页拿到这个参数的时候出现乱码情况,保持页面正常,那么,可能还要用到encodeURIComponent()和decodeURIComponent()了。
今天就到这里,谢谢各位观众老爷!