簡體   English   中英

Uncaught SyntaxError: Unexpected token ' in JSON at position 2

[英]Uncaught SyntaxError: Unexpected token ' in JSON at position 2

我有一個存儲在數據庫中的編碼字符串化 JSON 對象,我解碼並加載它並嘗試將它解析為一個對象但我得到

Uncaught SyntaxError: Unexpected token ' in JSON at position 2 at JSON.parse ()

代碼:

var attr = new Object();
attr = JSON.parse(code[1].replace(/"/g, "'"));

對象解碼:

[{'inputs':0,'type':'variable'},{'inputD':0,'type':'variable'},{'inputI':0,'type':'variable'},{ 'paras':0,'type':'variable'},{'headers':0,'type':'variable'},{'menus':0,'type':'variable'},{'lists ':0,'type':'variable'},{'divs':0,'type':'variable'},{'links':0,'type':'variable'},{'images': 0,'type':'variable'},{'elemName':'{}','type':'object'},{'borders':[],'type':'array'},{'nested ':[],'type':'array'},{'ribbons':[],'type':'array'},{'tooltips':[],'type':'array'},{' gradColors':'{}','type':'object'},{'events':'{}','type':'object'},{'sTarget':'{}','type': 'object'},{'sMain':'{}','type':'object'},{'orignalStyle':'{}','type':'object'},{'objNewStyle':'{ }','type':'object'},{'functions':'{}','type':'object'},{'reverse':'{}','type':'object'}, {'reverseFunction':'{}','type':'object'},{'scDetails':'{}','type':'object'}]

JSON 應該用雙引號括起來,例如:
{“輸入”:0,“類型”:“變量”}

這是一個有用的驗證工具:
https://jsonformatter.curiousconcept.com/

我有同樣的錯誤,@Philipp Zitzmann 是正確的。 您必須在https://jsonformatter.curiousconcept.com/ 提供有效的 json 字符串

有效的 json 字符串必須有雙引號。

JSON.parse({"u1":1000,"u2":1100})       // will be ok

沒有報價導致錯誤

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

單引號導致錯誤

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

不是有效的json 字符串。 它的值和鍵應該用雙引號(不是單引號)括起來。 因此,當您執行.replace(/"/g, "'")您基本上違反了 JSON 標准。

值可以是雙引號中的字符串、數字、真假或空值、對象或數組。 這些結構可以嵌套。

一個相關的。 今天我遇到了同樣的錯誤。 一個例子如下:

正確

JSON.parse( "[1,2,3,4,5,6,7,8,9,0]" )

不正確

JSON.parse( "[1,2,3,4,5,6,7,8,..." )

請注意 3 個點 (...),因為一個工具只顯示了數組中的幾個數字,並給出了 ... 以供休息。

換句話說,傳遞給JSON.parse()字符串是無效的,所以它給出了錯誤。

但它可以是任何其他類似的錯誤。

例如,(可能) JSON.parse( "true" )是正確的,但JSON.parse( "tr" )失敗,等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM