欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
JavaScript中 JSON.parse() 使用特性
在解析JSON字符串的时候,需要注意到JSON格式的一些规范,不然就容易报错。
JSON数据对值的类型和格式,都有严格的规定,具体的规则如下:
 
该方法使用字符串类型JSON格式数据。
该方法也支持数字、布尔值和null三个类型的值,转换出对应的字面值。
不支持其他类型。
JSON.parse('"中国"')
// '中国'
JSON.parse(null) // null
JSON.parse(111.) // 111
JSON.parse(0x12) // 18
JSON.parse(true) // true
JSON.parse([])
// Uncaught SyntaxError: Unexpected end of JSON input
字符串必须使用双引号,不能使用单引号。
JSON.parse('"String"')
// 'String'
JSON.parse('\'String\'')
// Uncaught SyntaxError: Unexpected token ' in JSON at position 0
只支持十进制的字符串,但小数点后必须跟上数字。
JSON.parse('111') // 111
JSON.parse('0x12')
// Uncaught SyntaxError: Unexpected token x in JSON at position 1
JSON.parse('111.232') // 111.232
JSON.parse('111.')
// Uncaught SyntaxError: Unexpected end of JSON input
不能使用undefined、Symbol和BigInt,数字也不支持NaN、Infinity和-Infinity,都会报错。
JSON.parse(undefined)
// Uncaught SyntaxError: Unexpected token u in JSON at position 0
JSON.parse(Symbol())
// Uncaught TypeError: Cannot convert a Symbol value to a string
JSON.parse('12n')
// Uncaught SyntaxError: Unexpected token n in JSON at position 2
复合类型,只能是:[] 和 {} 这样的字面量。
不能使用对象构造函数,因为会当作执行语句,不支持。
不能使用Object和Array,也不能是函数、RegExp对象、Date对象、Error对象等。
JSON.parse('[]')
// []
JSON.parse('Object()')
// Uncaught SyntaxError: Unexpected token O in JSON at position 0
对象的属性名必须使用双引号。
JSON.parse('{"key": 1 }')
// {key: 1}
JSON.parse('{key: 1 }')
// Uncaught SyntaxError: Unexpected token k in JSON at position 1
数组或对象最后一个成员的后面,不能加逗号。
JSON.parse('[1, 2, 3, 4, ]')
// VM2771:1 Uncaught SyntaxError: Unexpected token ] in JSON at position 13
JSON.parse('{"key" : 1, }')
// VM2779:1 Uncaught SyntaxError: Unexpected token } in JSON at position 12
支持unicode转义。
JSON.parse('{"\u0066":333}')
// {f: 333}
部分控制字符、转义字符不支持,如'\n'、'\t'等。
JSON.parse('"\n"')
// Uncaught SyntaxError: Unexpected token 
解析的其他方法
将json字符串转成json对象(js对象值),还可以使用其他方法,但是非安全代码。
 
const str = '{"name":"json","age":18}'
const json = JSON.parse(str)
const json = eval("(" + str + ")")
const json = (new Function("return " + str))()

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64535.shtml