Ошибка запроса к серверу parsererror syntaxerror unexpected end of json input

Делаю форму регистрации и столкнулся с проблемой.
ошибка: parsererror | SyntaxError: Unexpected end of JSON input

<form>
        <h3>Email</h3>
        <input id="email" class="empty" type="email" name="email" placeholder="example@example.com" value="<?php echo @$data['email']; ?>"><br>
        <h3>Birthsday</h3>
        <input id="birthsday" class="empty" type="text" name="birthsday" placeholder="dd/mm/yyyy" value="<?php echo @$data['birthsday']; ?>"><br>
        <h3>Password</h3>
        <input id="password" class="empty" type="password" name="password"><br>
        <h3>Confirm Password</h3>
        <input id="re_password" class="empty" type="password" name="re_password"><br>
      <input class="submit" type="button" value="Register">
    </form>
$('.submit').click(function () {
        var error = $('form').find('.not_error');
        
        if(error.length == 5) {
            var userEmail = $.trim($('#email').val());
            var userBirthsday = $('#birthsday').val();
            var userPass = $('#password').val();
            var userRePass = $('#re_password').val();

            $.ajax({
                type: 'POST',
                url: 'reg.php',
                dataType: 'json',
                data: {user_Email: userEmail, user_birthsday: userBirthsday, user_pass: userPass, user_RePass: userRePass},
                error: function(req, text, error) {
                    console.log('Ошибка AJAX: ' + text + ' | ' + error);
                },
                success: function (data) {
                    console.log('good');
                }
            });
        } else {
            ShowError();
    }
    });
require "db.php";

$data = $_POST;
if( isset($_POST['user_Email'], $_POST['user_birthsday'], $_POST['user_pass'], $_POST['user_RePass']) ) {
    
    //reg
    $errors = array();
    if(trim($data['user_Email']) == '') {
        $errors[] = 'Email';
    }
    
    $current_date = new DateTime(date('d.m.Y'));
    $date = new DateTime($data['user_birthsday']);
    
    if(trim($data['user_birthsday']) == '' || $date >= $current_date) {
        $errors[] = '2';
    }
    
    if(($data['user_pass']) == '') {
        $errors[] = '3';
    }
    
    if(($data['user_RePass']) != $data['user_pass']) {
        $errors[] = '4';
    }
    
    if(empty ($errors)) {
        $user = R::dispense('users');
        $user->email = $data['user_Email'];
        $user->birthsday = $data['user_birthsday'];
        $user->password = $data['user_pass'];
        R::store($user);
        $text = '<div style="color:gren;">good</div><br />';
    } else {
        $text = '<div style="color:red;">'.array_shift($errors).'</div><br />';
    }
}

The Javascript error “SyntaxError: Unexpected end of JSON input” happens when you try to use JSON.parse() on an incomplete JSON string. Check your string for missing curly brackets (}) and / or unclosed double-quotes.

In yet another installment of “why won’t my JSON parse?”, we have the incomplete JSON string. This error comes up a lot when receiving incomplete responses from the server and may not be entirely your fault. But it’s still probably a little your fault.

Below is an example of some offending code:

let incompleteJson = '{ "foo": "bar" ';
let myJavascriptObject = JSON.parse(incompleteJson);
console.log(myJavascriptObject.foo);

If we try to run this through a Node interpreter, we’ll get the following error:

undefined:1
{ "foo": "bar"
SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (/home/user/main.js:3:31)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
    at internal/main/run_main_module.js:17:47

Yikes! That looks scary. But what’s the problem here? Well, if you know anything about JSON, you’ll immediately see what the issue is: your JSON string contains an incomplete JSON object. What should end up parsing into an object with one property, foo, with the value of “bar”, is missing its closing curly bracket.

Fix 1: close the curly bracket

If we close that JSON object with a matching left curly bracket, our code will look like this instead:

let incompleteJson = '{ "foo": "bar" }';
let myJavascriptObject = JSON.parse(incompleteJson);
console.log(myJavascriptObject.foo);
// -> bar

Much better! But this is a super simple example. If you’re getting this on your production code, and your code is talking to an API, it’s a good bet the server is just sending you an incomplete response. This could be due to network trouble or some error on the server causing it to abort the connection mid-response.

Fix 2: use JSON.stringify() to make JSON strings

If you’re hard-coding your own JSON strings, you’re gonna have a bad time. That’s a computer’s job! Of course, JSON is so easy to write and read, it’s very tempting to make something like this right there in your sever-side (if your server is Node) or client-side code:

let badJson = "{ 'foo': 'bar' }";
let myJavascriptObject = JSON.parse(badJson);
console.log(myJavascriptObject.foo);

And then run into trouble later because, even though it looks correct, it’s not valid JSON. That’s because valid JSON only has double quotes, not single quotes. So then you figure “alright, I’ll just make ’em double quotes then!”. And you do something silly like this:

let badJson = '{ "foo": "bar }';
let myJavascriptObject = JSON.parse(badJson);
console.log(myJavascriptObject.foo);

And in your haste, you forgot the closing double-quote for the “bar” value, and now you have the same old “SyntaxError: Unexpected end of JSON input” you started with. Why is this so hard!? Because you’re trying to speak a totally different language than Javascript… inside a string… inside Javascript. That’s like, a lot of work. And very error prone.

Did you know Javascript has a built-in function so you don’t have to do this? Bet you didn’t. It’s called JSON.stringify() and apart from having a cool name, it can make your life a whole lot easier.

Observe:

let someObject = { foo: "bar" };
let myJsonString = JSON.stringify(someObject);
console.log(myJsonString);
// -> {"foo":"bar"}
let myObject = JSON.parse(myJsonString);
console.log(myObject.foo);
// -> bar

See that? Perfect JSON every time. That’s why making and reading JSON is best left up to computers. Yeah, it’s a popular serialization format because it’s human readable. But that doesn’t mean it’s supposed to be human write-able

(I know, lots of config files are now written in JSON. Leave me alone)

Fix 3: use jsonlint to check your JSON

Linters are super useful. They make sure your code isn’t dumb before you try to do stuff with it. jsonlint is a node package that can help you check your JSON before you wreck your JSON.

Install it like this:

Create a JSON file with the same contents as our broken string in the first example and save it as foo.json:

Then run jsonlint like this:

And you should have some output like the following:

Error: Parse error on line 1:
{ "foo": "bar"
--------------^
Expecting '}', ',', got 'EOF'
    at Object.parseError (/home/user/node_modules/jsonlint/lib/jsonlint.js:55:11)
    at Object.parse (/home/user/node_modules/jsonlint/lib/jsonlint.js:132:22)
    at parse (/home/user/node_modules/jsonlint/lib/cli.js:82:14)
    at main (/home/user/node_modules/jsonlint/lib/cli.js:135:14)
    at Object.<anonymous> (/home/user/node_modules/jsonlint/lib/cli.js:179:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)

Now that is a bit more helpful than “SyntaxError: Unexpected end of JSON input”, don’t you think? Our example is, again, trivial, but with a more complex JSON object to debug, you can see how jsonlint would be very useful.

Fix 4: catch the error

If you are expecting that you might get bad JSON and you just want to avoid your whole program crashing, you can also catch the error very simply:

let badJson = '{ "foo": "bar'
try {
    let myObject = JSON.parse(badJson);
    console.log(myObject.foo);
} catch (ee) {
    if (ee instanceof SyntaxError) {
        console.log("Oops, bad JSON!");
    } else {
        throw ee;
    }
}
// -> Oops, bad JSON!

Here, we wrap the JSON.parse() call in a try / catch block so that we can print an error message instead of having an unhandled exception float to the top of our call stack and make us look like a bunch of amateurs. Note that we are also making sure the exception is an instance of a SyntaxError so we don’t inadvertently catch something else and think it was the JSON syntax error. It’s just good practice to be specific in what exceptions you catch.

Conclusion

In this article we covered what causes “SyntaxError: Unexpected end of JSON input” and how to fix it, prevent it, or handle it. Which one of the fixes above you choose depends on your application. Sometimes, you might be getting JSON from the user, and you can’t assume it’ll be valid. So in that case it’s better to catch the error and deal with it. Otherwise, if you’re debugging something your API is returning to you, you may want to consider jsonlint or something similar.

Hope this helped. Till next time!

I can’t say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn’t hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there’s one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It’s when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don’t need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn’t return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

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

❌ Uncaught SyntaxError: Unexpected end of input

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

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

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

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

$(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');

  });

I can’t say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn’t hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there’s one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It’s when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don’t need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn’t return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

I can’t say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn’t hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there’s one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It’s when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don’t need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn’t return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

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

  1. С нами с:
    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. Команда форума
    Модератор

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

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

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

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

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

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

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

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

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

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

A common error encountered by JavaScript programmers is the Uncaught SyntaxError: Unexpected end of JSON input. This is usually observed when the coder is trying to convert a string into a JSON Object.

We will try to understand the cause of this error and how it can be solved. Let us look at an example.

Error Code:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
	  var jsondata = [''];
	  var jsonarray = JSON.parse(jsondata);
	  $.each(jsonarray, function(i, field){
		  $("div").append(field + " ");
      });
  });
});
</script>
</head>
<body>
<button>Get data</button>
<div></div>
</body></html>

Output:

Uncaught SyntaxError: Unexpected end of JSON input

We can observe here that the code raises the Uncaught SyntaxError: Unexpected end of JSON input.

In the program given above, the variable jsondata is assigned an empty string. In the next line, this variable is passed as an argument to the JSON.parse() method for parsing it. during parsing, it is converted into an empty string. So the end of the string is reached before parsing any possible content of the JSON text.

Let us look at the correct code.

Correct Code:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
	  var jsondata = ['{"Site":"Stechies", "Code":"Jquery"}'];
	  var jsonarray = JSON.parse(jsondata);
	  $.each(jsonarray, function(i, field){
		  $("div").append(field + " ");
      });
  });
});
</script>
</head>
<body>
<button>Get data</button>
<div></div>
</body></html>

Here, you can see that the variable jsondata is assigned data in the form of key-value pairs — «Site»: «Stechies», «Code»: «Jquery». So, while parsing using the JSON.parse() method, it is not converted into an empty string and hence the Uncaught SyntaxError is avoided.

I have Json data which I receive it as post data in my node.js server.

But the problem is, its not able to parse the string I sent.Here is my node.js server code.

res.header("Access-Control-Allow-Origin", "*");
  req.on('data',function(data)
  {
    var done=false;
    console.log(data);
    var schema;

    schema=JSON.parse(data);
   }

Here I get the error when I parse the json data(data).

undefined:776



SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/Users/as6/Documents/test/server.js:206:17)
    at emitOne (events.js:115:13)
    at IncomingMessage.emit (events.js:210:7)
    at IncomingMessage.Readable.read (_stream_readable.js:462:10)
    at flow (_stream_readable.js:833:34)
    at resume_ (_stream_readable.js:815:3)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)

I verified JSON data using JSONLint for syntax errors.But it was absolutely fine. I dont know what’s wrong and how to correct it.

asked Jul 11, 2017 at 8:56

Akash Sateesh's user avatar

1

data events can be fired multiple times, so you have to collect all the data values and concatenate them together when the end event has fires:

let chunks = [];

req.on('data', function(data) {
  chunks.push(data);
}).on('end', function() {
  let data   = Buffer.concat(chunks);
  let schema = JSON.parse(data);
  ...
});

However, perhaps you should consider using body-parser.

answered Jul 11, 2017 at 9:09

robertklep's user avatar

robertkleprobertklep

197k35 gold badges393 silver badges381 bronze badges

3

Do change the line

schema = JSON.parse(data);

into

schema = JSON.parse(JSON.stringify(data));

Skipper's user avatar

Skipper

7756 gold badges17 silver badges32 bronze badges

answered Jul 1, 2018 at 13:34

Owais Ibrahim's user avatar

“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.

You might have encountered the error “Uncaught SyntaxError: Unexpected end of JSON input” when using JSON.parse().

The error looks like this on the browser console (Google Chrome):

Uncaught SyntaxError raised in a promise

Uncaught SyntaxError raised in a promise

First of all, it’s not your code! What’s most likely wrong is the JSON string you’re trying to parse.

Woman thinking

When “Unexpected end of JSON input” is raised, your code is probably parsing:

  • An empty string
  • An empty array
  • Or an incomplete (a.k.a malformed) JSON data

That said, the first thing to examine is the JSON data.

If you’re using Google Chrome (like me), you can click the link on the right-hand side of the error message. 

It’s usually in the form of VM: Script ID, e.g., VM:1

If the log is empty, you’re probably dealing with an empty string! Otherwise, you’ll see the JSON data with an indicator.

How to fix the Uncaught SyntaxError: Unexpected end of JSON input

👇 Continue Reading

When working with JSON-formatted data in JavaScript, we’re either working with locally defined JSON data or fetching it from an API.

But how can we resolve the issue?

When working with locally defined JSON data: If you’re parsing local JSON content, the first thing to do is to ensure the variable isn’t empty. Maybe the variable is truncated for some reason.

If it’s not, you can validate your JSON-formatted data with an online JSON validator like JSONLint. If you have an invalid JSON object, you’ll find out here!

When working with a third-party JSON API: If you’re trying to parse a JSON API response, and you don’t have control over the back-end code, you can place your JSON.parse reference into a try/catch block – like so:


try {
  const data = JSON.parse(jsonData);
  // Do something with the JSON data
} catch (err) {
  console.error(err);
}


Wrapping up

The infamous «JSON input error» is a Syntax error usually raised when parsing empty or malformed JSON data. Fixing this issue is easy when dealing with locally-defined JSON data. 

👇 Continue Reading

If you don’t have control over the back-end code generating the JSON data, a try/catch block would help you avoid the «Uncaught SyntaxError» error.

Additionally, you might find this Mozilla guide on JSON.parse to avoid other types of parse errors.

I hope this quick guide provided the answer you were looking for.

Thanks for reading.

Author photo

Reza Lavarian Hey 👋 I’m a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rlavarian

  • Ошибка запроса к серверу object reference not set to an instance of an object
  • Ошибка запроса к серверам вк бот дискорд
  • Ошибка запроса к grandsmeta ru
  • Ошибка запроса к api что это
  • Ошибка запроса к api дгту