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))// 报错

若你对JSON.stringify()JSON.parse()区别有所疑惑,以及它们在实际开发中有哪些作用,欢迎阅读博主 json.stringify()的妙用,json.stringify()与json.parse()的区别 这篇文章。

希望对你有所帮助,那么本文到此结束。

猜你喜欢

转载自www.cnblogs.com/echolun/p/11720161.html