0

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:

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);

1
  • you need to replace /r/n using regex and then do JSON.parse Commented Oct 19, 2014 at 19:52

3 Answers 3

2

Since you have ;BağdatCad.HeperApt.\r\n in string, that was causing error , it was showing invalid 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);

Sign up to request clarification or add additional context in comments.

Comments

1

Your json is not valid (jsonlint.com).

you need to replace the new lines with \\n too.

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

Comments

0

Your text has new lines in it: 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).

These are not allowed in JSON strings and must be replaced by escape sequences.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.