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()的區別 這篇文章。

希望對你有所幫助,那么本文到此結束。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM