This is what i get as logs
Error occurs at response.json()
call. Interesting thing is, this call works fine if i set chrome remote debug on. It works fine in iOS 10.0 (didn’t test in earlier version)
11-01 08:53:27.036 32587 4288 I ReactNativeJS: { type: 'default',
11-01 08:53:27.036 32587 4288 I ReactNativeJS: status: 200,
11-01 08:53:27.036 32587 4288 I ReactNativeJS: ok: true,
11-01 08:53:27.036 32587 4288 I ReactNativeJS: statusText: undefined,
11-01 08:53:27.036 32587 4288 I ReactNativeJS: headers:
11-01 08:53:27.036 32587 4288 I ReactNativeJS: { map:
11-01 08:53:27.036 32587 4288 I ReactNativeJS: { date: [ 'Tue, 01 Nov 2016 03:23:21 GMT' ],
11-01 08:53:27.036 32587 4288 I ReactNativeJS: server: [ 'Microsoft-HTTPAPI/2.0' ],
11-01 08:53:27.036 32587 4288 I ReactNativeJS: 'content-type': [ 'application/json' ],
11-01 08:53:27.036 32587 4288 I ReactNativeJS: 'content-length': [ '187' ] } },
11-01 08:53:27.036 32587 4288 I ReactNativeJS: url: 'http://xx.xx.xx.xx/Service/json/xxxx',
11-01 08:53:27.036 32587 4288 I ReactNativeJS: _bodyInit: '{rn "Command": 20020,rn "Id": 216,rn "Name": "Tester",rn "Email": "cc@cc.com",rn "Tel": "(012) 345-6712",rn "Pass": null,rn "IsActive": true,rn "HasAccount": falsern}',
11-01 08:53:27.036 32587 4288 I ReactNativeJS: _bodyText: '{rn "Command": 20020,rn "Id": 216,rn "Name": "Tester",rn "Email": "cc@cc.com",rn "Tel": "(012) 345-6712",rn "Pass": null,rn "IsActive": true,rn "HasAccount": falsern}' }
Above is the response which i get from the API call
11-01 08:53:27.042 32587 4288 I ReactNativeJS: { [SyntaxError: JSON Parse error: Unrecognized token '?']
11-01 08:53:27.042 32587 4288 I ReactNativeJS: line: 30380,
11-01 08:53:27.042 32587 4288 I ReactNativeJS: column: 10,
11-01 08:53:27.042 32587 4288 I ReactNativeJS: sourceURL: 'http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false' }
JSON.parse() выдает ошибку «неожиданный токен» для правильного JSON
При работе с JSON порой происходит нечто непонятное — хотя строка JSON
вроде бы и правильная, метод JSON.parse, выдает ошибку “unexpected
token”. Это связано с тем, что JSON.parse не может разобрать некоторые
специальные символы, такие как n, t, r и f. Поэтому и бросается
исключение.
Поэтому, чтобы данное исключение не бросалось, необходимо экранировать эти
специальные символы, прежде чем передавать строку JSON в функцию
JSON.parse.
Вот функция, которая берет строку JSON и экранирует специальные символы:
function escapeSpecialChars(jsonString) {
return jsonString.replace(/n/g, "\n")
.replace(/r/g, "\r")
.replace(/t/g, "\t")
.replace(/f/g, "\f");
}
Таким образом вы можете решить ошибку «unexpected token» при работе с JSON.
-
Создано 19.06.2018 08:53:04
-
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:
-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
This guide will help you to fix SyntaxError: Unexpected token < in JSON at position 0
. This guide also applies to these other common variants of the same error:
-
SyntaxError: The string did not match the expected pattern.
-
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
-
JSON parse error: Unrecognised token '<'
Summary
These errors indicate that your JavaScript code expected to receive JSON but got something else instead (probably HTML in the form of a server-side error). To fix the issue, you need to examine what you got instead of the expected JSON to determine what the problem is.
Details
Usually, this error is caused when your server returns HTML (which typically begins with <DOCTYPE html>
or <html>
) instead of JSON. Valid JSON cannot begin with a <
character, so the JSON parser knows immediately that the data isn’t valid JSON and produces one of the error messages mentioned above.
To fix this error, you need to figure out why you’re getting HTML (or something else) instead of the JSON you expected. To do this, you need to log the data that you’re trying to parse to the console.
If you’re using fetch()
Use this approach if your code looks something like this:
fetch('https://example.com/some/path/to/json') .then(function (response) { return response.json(); }) .then(function (data) { // Do something with data });
In this case, the error is thrown when response.json()
tries to run and fails to parse the data from the server as JSON. You can add a function to handle the error, display the raw text of the response body from the server and log it to the console (see notes about commented lines below):
var responseClone; // 1 fetch('https://example.com/some/path/to/json') .then(function (response) { responseClone = response.clone(); // 2 return response.json(); }) .then(function (data) { // Do something with data }, function (rejectionReason) { // 3 console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4 responseClone.text() // 5 .then(function (bodyText) { console.log('Received the following instead of valid JSON:', bodyText); // 6 }); });
Here’s an explanation of each line with a numbered comment:
-
A
responseClone
variable is required to hold a clone of theresponse
object because the body of aresponse
can only be read once. Whenresponse.json()
is called, the body of the originalresponse
is read, which means it cannot be read again while handling the JSON parse error. Cloning theresponse
toresponseClone
provides two copies of the response body to work with; one in the originalresponse
to use withresponse.json()
and another to use withresponseClone.text()
ifresponse.json()
fails. -
This line populates the
responseClone
variable with a clone of the response received from the server. -
A second function argument is passed to the
then()
function that follows theresponse.json()
call. This second function will be called if the promise fromresponse.json()
is rejected (i.e. a JSON error is encountered). -
This line logs the
rejectionReason
from the rejectedresponse.json()
promise and theresponseClone
so it can be examined if needed (the HTTP status code is often useful for debugging, for example). -
Instead of trying to parse the response body from the server as JSON, it is processed as raw text.
-
The body text is logged to the console for examination.
If you’re using JSON.parse()
Use this method if the code that’s throwing the error looks like this:
JSON.parse(data);
In this case, you can log the data to the console if an error is encountered to see what it contains:
try { JSON.parse(data); } catch (error) { console.log('Error parsing JSON:', error, data); }
What do I do next?
Once you can see the data that’s causing the JSON parse error, it will hopefully provide a clue as to why you’re not getting the valid JSON you expect. Some of the most common issues that lead to this error are:
-
If you see HTML indicating a 404 Not Found error instead of the JSON you expect, check the URL you’re passing to
fetch()
and make sure that it’s correct. -
If you see HTML indicating a server error (such as a 500 error code), examine your server’s error logs to determine why your server is encountering an error instead of providing the JSON you expect.
-
If you cannot see anything or if you have an unusual jumble of characters, check your variable assignments and character encodings.