JSON.parse导致Unexpected Token错误消息

时间:2014-10-19 19:44:36

标签: javascript json

对不起这个问题可能会被问到几百次,我找了类似的问题,但我找不到线索,为什么我仍然收到这个错误。

当我尝试解析下面的这个特定字符串时,它会显示“语法错误:意外令牌”。这是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);

3 个答案:

答案 0 :(得分:2)

由于您在字符串中有;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);




答案 1 :(得分:1)

您的json无效(jsonlint.com)。

您还需要用\\n替换新行。

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

答案 2 :(得分:0)

您的文字中有新行:Apt. \r\nNo:165/。 (注意,它们将被转换为实际的新行,JavaScript解析器将JavaScript源代码解析为字符串)。

这些在JSON字符串中是不允许的,必须由转义序列替换。