JSON.parse解决Unexpected token ' in JSON at position 1报错

JSON.parse解决Unexpected token ' in JSON at position 1报错

 壹 ❀ 引

我们知道JSON.parse能将JSON字符串转变成JS对象,但在一些转换中可能出现Unexpected token ' in JSON at position 1的错误,这是因为被转换的值不符合JSON格式而造成的。

JSON官方明确规定,JSON数据的key与value必须使用双引号""包裹,否则在转换过程中会导致错误。

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

 贰 ❀ 示例

复制代码
// 数组
let a = '["a","b","c"]';// √
let b = "['a','b','c']";// X

// 对象
let a1 = '{"name":"听风是风","age":"26"}';// √
let b1 = "{'name':'听风是风','age':'26'}";// X

console.log(JSON.parse(a))// Array
console.log(JSON.parse(a1))// Object
console.log(JSON.parse(b))// 报错
console.log(JSON.parse(b1))// 报错
复制代码

 

 

本文转自:  https://www.cnblogs.com/echolun/p/11720161.html

posted @ 2019-12-18 10:54  前端邢晋宇  阅读(3364)  评论(0编辑  收藏  举报