Syntax error unexpected end of json input parsererror

This short article will try to clarify a few things about the "Unexpected end of JSON input" error and possible steps to fix it.

“Unexpected end of JSON input” (or “Uncaught SyntaxError: Unexpected end of JSON input”) is a common error message in JavaScript, occurs when the user tries to convert an invalid JSON string into a native JS object using JSON.parse() method. This short article will try to clarify a few things about the error and possible steps to fix it.

The full form of the message would look like this in the browser’s Console.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at <your-script-name.js>

Code language: JavaScript (javascript)

Unexpected end of JSON input in Chrome console

“Unexpected end of JSON input” root cause is a malformed string passed into the JSON.parse() method.

In most cases, it is due to a missing character in the last position of a JSON string that wraps its objects (such as a closing square bracket [] or curly bracket {}).

Sometimes, you may be trying to read an empty JSON file. A valid empty JSON file would still need to have curly brackets to indicate that it contains an empty object.

// empty.json file contents {}

Code language: JSON / JSON with Comments (json)

Let’s look at two examples below to clearly understand what’s missing

  Code containing errors Corrected code.
1 var my_json_string = '{"prop1": 5, "prop2": "New York"'; var data = JSON.parse(my_json_string); var my_json_string = '{"prop1": 5, "prop2": "New York"}'; var data = JSON.parse(my_json_string);
2 var my_json_string = '[1, "yellow", 256, "black"'; var data = JSON.parse(my_json_string); var my_json_string = '[1, "yellow", 256, "black"]'; var data = JSON.parse(my_json_string);

In the first example, there’s a missing closing curly bracket at the end of the string. Meanwhile, the second example demonstrate a malformed JSON string with the closing square bracket truncated.

Also check out: Object of type is not JSON serializable in Python

How to fix “Unexpected end of JSON input”

  1. Locate a statement using the JSON.parse() method. On the browser’s console, click on the last line of the exception message (which is a reference to the code block that raised that exception). The browser will then bring you to the actual source code.
  2. Inspect the input of JSON.parse(). Now there are many ways to do this. You can take a close look at the data to spot the error. Usually it’s in the beginning or the end of the string.
  3. If you use popular code editor software like VS Code, Sublime Text, Atom, you’ll also have another way to check the syntax of JSON data: Copy all that JSON data to a completely new file, the default formatter of the software will highlight the syntax error location.
  4. Alternatively, the browser Console also supports highlighting common JSON syntax error. You would need to click VMxx:x right next to the exception message.image-20211020085539363

Conclusion

We hope that the article helps you understand why “Unexpected end of JSON input” happens and how you can correct the input to fix it. If you do a lot of JSON manipulation in JavaScript, you may want to check out our guide on JSON end of file expected, which is another very common one. If you have any suggestions or spot an error in the article, feel free to leave a comment below to let us know.

Ezoic

Ситуация: вы пишете скрипт, в котором объявляете новые функции или используете уже встроенные. Вы уверены, что всё правильно, потому что делали так сотни раз в других проектах, но при запуске кода появляется такая ошибка:

❌ Uncaught SyntaxError: Unexpected end of input

Что это значит: браузер ждёт от вас или от кода продолжения ввода параметров или новых значений, но не находит их и падает с ошибкой.

Когда встречается: чаще всего это значит, что вы где-то потеряли закрывающие скобки. Вторая ситуация, более редкая — вы обрабатываете JSON-запрос и вам просто не приходят нужные данные (хотя должны бы). О том, что такое JSON-запросы и ответы, будет в отдельной статье — тема слишком большая и интересная для короткого ответа. Сейчас остановимся на первом варианте.

Что делать с ошибкой Uncaught SyntaxError: Unexpected end of input

Чтобы отловить и исправить эту ошибку, вам нужно посчитать и сравнить количество открытых и закрытых скобок в программе — как круглых (), так и фигурных {}. Скорее всего, вам не хватает и того, и другого (и точки с запятой после них).

Проще всего такую ошибку найти простым форматированием кода: когда все вложенные команды и параметры сдвигаются вправо табуляцией или пробелами. В этом случае легко найти разрыв в получившейся лесенке кода и добавить туда нужные скобки. Смотрите сами:

$(function () {
  $("#mewlyDiagnosed").hover(function () {
    $("#mewlyDiagnosed").animate({ 'height': '237px', 'top': "-75px" });
  }, function () {
    $("#mewlyDiagnosed").animate({ 'height': '162px', 'top': "0px" });
  });

Может показаться, что всё в порядке, но вот как выглядит этот код после форматирования:

$(function () {
  $("#mewlyDiagnosed").hover(function () {
    $("#mewlyDiagnosed").animate({ 'height': '237px', 'top': "-75px" });
  }, function () {
    $("#mewlyDiagnosed").animate({ 'height': '162px', 'top': "0px" });
  });

Сразу видно, что в конце скрипта не хватает строки с )}; — если их не поставить, браузер будет ждать продолжения ввода параметров вызова функции, не дождётся их и выдаст ошибку Uncaught SyntaxError: Unexpected end of input

Попробуйте сами. Найдите ошибку в этом коде:

$(function() {

  // Script to select all checkboxes

  $state.on('change', function(ev) {

    var $chcks = $("#example tbody input[type='checkbox']");

    if($state.is(':checked')) {

      $chcks.prop('checked', true).trigger('change');

    }else {

      $chcks.prop('checked', false).trigger('change');

  });

Code formatting. Tabs or spaces, semi-colons or no semi-colons. It is a pretty controversial subject to many but it is quite important in some instances. If you are on a team, having a cohesive code format helps code readability among your peers. Even if you work alone, one big benefit of having a good sense of code formatting is to avoid syntactical errors.

JavaScript is pretty open when it comes to code format. There is a wide range of different ways to format your codebase in this language. What can happen if you don’t do it? Well, an example of a simple error that is often caused by code formatting issues is the Unexpected end of input error. How does it work?

The Problem

When JavaScript code is run it uses just in time compilation (JIT) to turn your code into something the computer can do. When this happens your code is read and certain things are expected about the code, for example having matching parentheses. If you received the Unexpected end of input error, odds are you are missing a closing curly brace } so the error is basically saying “you opened the curly brace but the code ended before it was closed”.

Here’s an example:

const writeHelloWorld = () => { console.log('hello world') writeHelloWorld();

Code language: JavaScript (javascript)

As you can see, the code is clearly missing a ending curly brace at the end of the arrow function which causes the error. So how does the code formatting mentioned earlier fit into this? Let’s look at a more real-world example:

const items = ['one', 'two', 'three']; function parseItems() { for (let i = 0; i < items.length; i++) { if (items[i]) { console.log(items[i]) } } parseItems();

Code language: JavaScript (javascript)

In this example, it is a little less clear where the error is. The indentation is not very consistent so you might not notice that the if statement is actually missing a curly brace after which causes the error.

The Solution

Fortunately this is pretty simple to fix — you can just add your missing curly brace. In the above example:

const items = ["one", "two", "three"]; function parseItems() { for (let i = 0; i < items.length; i++) { if (items[i]) { console.log(items[i]); // indented this line over } // added this curly brace } } parseItems();

Code language: JavaScript (javascript)

It can definitely be challenging to find a missing curly brace. Depending on your code editor of choice, you may be able to configure different colors for each pair of curly brace so it is easier to see which ones match and which ones don’t.

Another approach is to try and avoid these errors from the start. Using formatting tools such as Prettier or linting tools like ESLint can help a lot, at least in my experience.

Unexpected end of JSON input

There’s a chance that you received a similarly named but slightly different error: Unexpected end of JSON input. Rather than simply a missing curly brace, this error often occurs when you are trying to parse a JSON string that is itself missing a curly brace. Here’s an example:

const parseJson = (input) => JSON.parse(input); const validJson = JSON.stringify({ hello: "world" }); const invalidJson = "{"; console.log(parseJson(validJson)); // prints out a valid object console.log(parseJson(invalidJson)); // throws an error

Code language: JavaScript (javascript)

This can be simply fixed by ensuring the string you are parsing is valid JSON if you have control over that string. If you don’t, you can wrap the whole thing in a try / catch to be safe. Using the previous example:

const parseJson = (input) => { try { return JSON.parse(input); } catch (error) { return "error parsing input"; } };

Code language: JavaScript (javascript)

If you add this to the parseJson function, you can now handle invalid JSON strings rather than getting an unexpected runtime error.

Conclusion

Hopefully this helps you see how useful good code formatting can be in your code, whether you work with a team or alone. Let us know if you have any other reasons why formatting can be so useful or how you do it in your own code setup. Thanks for reading!

За последние 24 часа нас посетили 11584 программиста и 1164 робота. Сейчас ищут 309 программистов …


  1. Иван27

    С нами с:
    25 июн 2017
    Сообщения:
    29
    Симпатии:
    0

    Почему выдает ошибку syntaxerror unexpected end of json input?
    Сам индекс

    1. <link rel=«stylesheet» type=«text/css» href=«css/bootstrap-theme.css»>
    2.   <link rel=«stylesheet» type=«text/css» href=«css/bootstrap.css»>
    3.   <link rel=«stylesheet» type=«text/css» href=«css/promo.css»>
    4.   <link rel=«stylesheet» type=«text/css» href=«css/animate.css»>
    5.   <link rel=«shortcut icon» href=«img/favicon.ico» type=«image/x-icon»>
    6.   <script type=«text/javascript» src=«../js/jquery-2.1.4.min.js»></script>
    7. <form method=«POST» action=«» id=«slick-login»>
    8.    <input id=«input» type=«text» name=«promocode» class=«placeholder» placeholder=«XXXX-XXXX-XXXX»>
    9.     <input name=«submit» type=«submit» value=«Активировать» «>
    10. <script type=«text/javascript»>
    11. $(document).ready(function() {
    12.   $(«#slick-login»).submit(function(){
    13.     form.find(‘input’).each( function(){
    14.       if ($(this).val() == ») {
    15.         alert(‘Зaпoлнитe пoлe «‘+$(this).attr(‘placeholder’)+'»!’);
    16.       var data = form.serialize();
    17.            beforeSend: function(data) {
    18.                 form.find(‘input[type=»submit»]’).attr(‘disabled’, ‘disabled’);
    19.            error: function (xhr, ajaxOptions, thrownError) {
    20.            complete: function(data) {
    21.                 form.find(‘input[type=»submit»]’).prop(‘disabled’, false);
    22. <!— Scripts —><script type=«text/javascript» src=«https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js»></script>

    обработчик формы

    1.   $promocode = ($_POST[«promocode»]);
    2.    if(!preg_match(«/^[a-zA-Z0-9]+$/»,$_POST[‘promocode’]))
    3.     $json[‘error’] = ‘Промокод может состоять только из букв английского алфавита и цифр’;
    4.     if(strlen($_POST[‘promocode’]) < 3 or strlen($_POST[‘promocode’]) > 12)
    5.        $json[‘error’] = ‘Промокод должен быть не меньше 3-х символов и не больше 12’;
    6.     function mime_header_encode($str, $data_charset, $send_charset) { // функция прeoбрaзoвaния зaгoлoвкoв в вeрную кoдирoвку
    7.     if($data_charset != $send_charset)
    8.     $str=iconv($data_charset,$send_charset.‘//IGNORE’,$str);
    9. $mysqli->set_charset(‘utf8’);
    10. $promocode = $mysqli->real_escape_string($_POST[‘promocode’]);
    11. $query = $mysqli->query(«SELECT `promocode` FROM `action` WHERE `promocode` = ‘$promocode‘»);
    12. $result = mysql_query(«SELECT * FROM action WHERE promocode=’$promocode‘»,$db);
    13. $comment=$row[‘comment’];
    14. if($query != false && $query->num_rows >= 1)
    15.   $json[‘error’] = ‘Ваш приз $comment $price’;

    Простите за ужасный код.


  2. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Потому что вместе с JSON-ом или вместо него пришло что-то другое. Мб у тебя там где-то нотис выводится или еще что. За этим надо следить. Открывай инструменты разработчика в браузере, панель networking, делай на странице запрос, а потом смотри его содержимое и содержимое ответа в инструментах разработчика.
    — Добавлено —
    И да, выкинь денвер, поставь хотя бы openserver и работай на Php7.1+ сразу.
    Первым делом ты удивишься тому, что у тебя все работать перестало. Потом узнаешь, что расширение mysql_ уже сто лет как устарело(как и денвер, и версия Php, которую он предлагает по дефолту) и в современном php выброшено на мороз. Юзай вместо него mysqli_.
    — Добавлено —
    За обратные кавычки в запросах и использование эскейпинга плюсик тебе в виртуальную карму. Если, конечно, ты — автор кода.
    — Добавлено —
    А вот за отсутствие архитектуры хоть какой-то, минусик в виртуальную карму. Проектирование нужно подтягивать. Коннект к бд можно было бы вынести и в отдельную функцию как минимум.


  3. Иван27

    С нами с:
    25 июн 2017
    Сообщения:
    29
    Симпатии:
    0

    Я и так использую open server. А вот что выдает » {«error»:»u041fu0440u043eu043cu043eu043au043eu0434 u043cu043eu0436u0435u0442 u0441u043eu0441u0442u043eu044fu0442u044c u0442u043eu043bu044cu043au043e u0438u0437 u0431u0443u043au0432 u0430u043du0433u043bu0438u0439u0441u043au043eu0433u043e u0430u043bu0444u0430u0432u0438u0442u0430 u0438 u0446u0438u0444u0440″}


  4. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Если бы было именно так и корректно отдавалось JSON-парсеру, то все бы работало. Там же, в инструментах разработчика, ставь брейкпоинты перед обработкой ответа сервера, и смотри, что реально пытаешься скормить скрипту.


  5. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Тогда самое время переключиться на php7.1+

“SyntaxError: Unexpected end of input” problem often occurs when we miss a closing parenthesis, bracket, or quote. Check out our instructions below to find the best solution that works for you.

  • Find more about JS Type of Errors

What causes the error “SyntaxError: Unexpected end of input”?

Reproduce the “SyntaxError: Unexpected end of input” in JavaScript

Let’s take a look at one example:

function hello() {
  console.log('Welcome to LearnShareIt.com');

hello();

In this example, we can easily spot that a parenthesis is missing. Therefore, you will receive the Unexpected end of input error. To make it easier for you to understand, this simply means that the computer is telling you: “Hey man, you opened the parenthesis but forgot to close it.”

Here is another example: 

const obj = JSON.parse('');

When you are trying to parse an empty JSON string with JSON.parse(), it might also lead to getting the Unexpected end of input error

Solution 1: Add the missing parenthesis, bracket or quote!

The easiest way to fix this problem is to just add the closing parenthesis, bracket, or quote. 

function hello() {
  console.log('Welcome to LearnShareIt.com');
} 

hello();

Output:

Welcome to LearnShareIt.com

The parenthesis works like a door. If you open it, then you have to close it so that your program will work properly.

Solution 2: Use extensions/tools

We can use solution 1 without any problems for small projects or exercises. But for real-world larger projects, it is not always easy to do so. Let’s take a look at an example: 

const array = [1, 2, 3, 4, 5];

function even(){
  for (let i=0; i<5; i++) {
    if (array[i]%2===0){
      console.log(array[i]);
  }
}

even();

As you can see, the errors are less obvious in this example. Since then, we can use some online JavaScript Syntax Validators found easily on the Internet to help us check the syntax of our code.

Fixed code:

const array = [1, 2, 3, 4, 5];

function even(){
  for (let i=0; i<5; i++) {
    if (array[i]%2===0){
      console.log(array[i]);
    }
  }
}

even();

Output:

2
4

Solution 3: Avoid parsing empty JSON string

Make sure that your string is not empty before parsing.

Summary

The “SyntaxError: Unexpected end of input” error in JavaScript can be caused by various reasons, but the most common one is that we forget a closing parenthesis, bracket, or quote. To make it easier to handle large programs or projects, we can use a JavaScript validator to double-check the syntax.

Maybe you are interested in similar errors:

  • ReferenceError: document is not defined
  • Unexpected token u in JSON at position 0
  • Uncaught SyntaxError: Unexpected token
  • Unexpected token o in json at position 1 error in js

Hello. My name is Khanh Hai Ngo. I graduated in Information Technology at VinUni. My advanced programming languages include C, C++, Python, Java, JavaScript, TypeScript, and R, which I would like to share with you. You will benefit from my content.


Name of the university: VinUni
Major: EE
Programming Languages: C, C++, Python, Java, JavaScript, TypeScript, R

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected end of input javascript
  • Syntax error unexpected end and premature end of file
  • Syntax error unexpected else expecting
  • Syntax error unexpected character after line continuation character
  • Syntax error unexpected bash array