[英]JSON.parse resulting Unexpected Token error message
Sorry this question might be asked hundreds time, I looked for similar questions but I can not find a clue why I still receive this error. 抱歉,这个问题可能被问了数百遍,我一直在寻找类似的问题,但是我找不到为什么仍然收到此错误的线索。
When I try to parse this specific string below, it says "Syntax error: Unexpected token". 当我尝试在下面解析此特定字符串时,它显示“语法错误:意外的令牌”。 This is JS code:
这是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);
Since you have ;BağdatCad.HeperApt.\\r\\n
in string, that was causing error , it was showing invalid JSON
. 由于您在字符串中包含
;BağdatCad.HeperApt.\\r\\n
,这会导致错误,它显示了无效的JSON
。 You need to replace them with space or blank string using regex. 您需要使用正则表达式将它们替换为空格或空白字符串。 So Correct code would be.
因此正确的代码将是。
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);
Your json is not valid ( jsonlint.com ). 您的json无效( jsonlint.com )。
you need to replace the new lines with \\\\n
too. 您还需要用
\\\\n
替换新行。
// additional replace func call
a = a.replace(/(?:\r\n|\r|\n)/g, '\\n');
Your text has new lines in it: Apt. \\r\\nNo:165/
您的文字中包含新行:
Apt. \\r\\nNo:165/
Apt. \\r\\nNo:165/
. Apt. \\r\\nNo:165/
。 (Note, they will be converted to actual new lines with the JavaScript parser parses the JavaScript source code into the string). (请注意,它们将通过JavaScript解析器转换为实际的新行,将JavaScript源代码解析为字符串)。
These are not allowed in JSON strings and must be replaced by escape sequences. 这些在JSON字符串中是不允许的,并且必须由转义序列替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.