2014-10-19 78 views
0

對不起,這個問題可能會被問幾百次,我尋找類似的問題,但我無法找到一個線索,爲什麼我仍然收到此錯誤。JSON.parse導致意外的令牌錯誤消息

當我嘗試解析下面的特定字符串時,它會顯示「語法錯誤:意外的標記」。這是JS代碼:

var a = "[{"ltd":"40.88393692299686","lng":"29.40516471862793","country":"Türkiye","city":"İstanbul","address":"Tepeören Mh., 2. Caddesi, 41480 Istanbul-Istanbul Province, Turkey","title":"Indoor Life Facory","detail":"İTOSB 2.Cad. No.7 Tuzla/istanbul/Turkey","addressTypeId":1,"adressType":"Üretim Birimi"},{"ltd":"40.97575903170847","lng":"29.051960706710815","country":"Türkiye","city":"İstanbul","address":"Fenerbahçe Mh., Bağdat Avenue 184-190, 34724 Kadıköy-Istanbul Province, Turkey","title":"Indoor Life Head Office","detail":"Bağdat Cad. Heper Apt. \r\nNo:165/5 34730 \r\nSelamiçeşme/Kadıköy/İstanbul/Turkey","addressTypeId":2,"adressType":"İdari Birim"}]"; 
 
a = a.replace(/"/g, '"'); 
 
var jsonList = JSON.parse(a);

+0

需要更換'/ R/N'使用正則表達式,然後做JSON.parse – 2014-10-19 19:52:51

回答

1

由於您有字符串中的;BağdatCad.HeperApt.\r\n,這是導致錯誤,它顯示無效JSON。你需要用正則表達式替換空格或空白字符串。所以正確的代碼會是。

var a = "[{"ltd":"40.88393692299686","lng":"29.40516471862793","country":"Türkiye","city":"İstanbul","address":"Tepeören Mh., 2. Caddesi, 41480 Istanbul-Istanbul Province, Turkey","title":"Indoor Life Facory","detail":"İTOSB 2.Cad. No.7 Tuzla/istanbul/Turkey","addressTypeId":1,"adressType":"Üretim Birimi"},{"ltd":"40.97575903170847","lng":"29.051960706710815","country":"Türkiye","city":"İstanbul","address":"Fenerbahçe Mh., Bağdat Avenue 184-190, 34724 Kadıköy-Istanbul Province, Turkey","title":"Indoor Life Head Office","detail":"Bağdat Cad. Heper Apt. \r\nNo:165/5 34730 \r\nSelamiçeşme/Kadıköy/İstanbul/Turkey","addressTypeId":2,"adressType":"İdari Birim"}]"; 
 
a = a.replace(/"/g, '"'); 
 
a = a.replace(/(?:\r\n|\r|\n)/g, ''); 
 
console.log(a); 
 
var jsonList = JSON.parse(a);

+0

謝謝,它的工作。 – isidat 2014-10-20 05:09:15

1

您的JSON是無效的(jsonlint.com)。

您也需要用\\n替換新的行。

// additional replace func call 
a = a.replace(/(?:\r\n|\r|\n)/g, '\\n'); 
0

您的文字上有新行:Apt. \r\nNo:165/。 (請注意,JavaScript解析器會將JavaScript源代碼解析爲字符串,它們將轉換爲實際的新行)。

這些在JSON字符串中是不允許的,必須用換碼序列替換。