Syntaxerror unexpected end of json input ошибка

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.

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

Cover image for About "SyntaxError: Unexpected end of JSON input" in JavaScript

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

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

Image description

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

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

  1. An empty string
  2. An empty array
  3. 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

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

Enter fullscreen mode

Exit fullscreen mode

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.

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.

Делаю форму регистрации и столкнулся с проблемой.
ошибка: 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 />';
    }
}

Ошибка “Unexpected end of JSON input” – это синтаксическая ошибка, которая возникает, когда JSON, который вы пытаетесь разобрать, является неполным или недействительным.

Эта ошибка обычно возникает, когда вы пытаетесь разобрать JSON с помощью метода JSON.parse(), а строка JSON, которую вы ему передаете, является неполной или недействительной. Например, если вы пытаетесь разобрать следующий JSON:

{ "name": "John Doe" "age": 30 }

Вы получите ошибку “Unexpected end of JSON input”, потому что в JSON отсутствует запятая между свойствами “name” и “age”.

Правильный JSON будет выглядеть следующим образом:

{
  "name": "John Doe",
  "age": 30
}

Итак, вам необходимо убедиться, что JSON, который вы пытаетесь разобрать, является полным и валидным. Вы можете использовать JSON linter или JSON validator для проверки правильности JSON и исправления любых синтаксических ошибок.

Когда localStorage заполнено

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

Это также может произойти, если другое приложение уже использует ключ, который вы пытаетесь разобрать, и его нельзя перезаписать.

function saveUserData(user) {
  const json = JSON.stringify(user);
  localStorage.setItem('user', json);
}

const user = {
  name: 'John Doe',
  email: 'johndoe@gmail.com',
  password: 'p@ssw0rd'
};

saveUserData(user);

В этом случае вы можете добавить блок try/catch в функцию saveUserData и использовать console.log для вывода сообщения об ошибке в консоль, как показано ниже:

function saveUserData(user) {
  try {
    const json = JSON.stringify(user);
    localStorage.setItem('user', json);
  } catch (error) {
    console.log(error.message);
  }
}

При таком изменении, когда вызывается функция saveUserData, она попытается сохранить объект user в локальном хранилище. Если произойдет ошибка, будет выполнен блок catch и сообщение об ошибке будет выведено на консоль.

К сожалению, нет возможности перечислить все сценарии, в которых может возникнуть эта ошибка. Если вы посмотрите на сайты вроде StackOverflow, то увидите, что большинство людей спрашивают не конкретно об ошибке, а о коде, который приводит к этой ошибке. В этом контексте вам нужно выяснить, из-за чего ваш вывод JSON не является корректным.

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

Входные данные JSON неправильно отформатированы:

const json = '{ "key": "value"';

Ввод JSON содержит синтаксическую ошибку:

const json = '{ "key": "value" error }';

Во входном файле JSON пропущена или лишняя запятая:

const json = '{ "key": "value", "key2": "value2" "key3": "value3" }';

Во входном файле JSON пропущена или лишняя фигурная скобка:

const json = '{{ "key": "value" "key2": "value2" }';

При вводе JSON пропущена или лишняя квадратная скобка:

const json = '{ "key": "value", "key2": ["value2", "value3"]] }';

Во входном файле JSON пропущена или лишняя кавычка:

const json = '{ key: "value", "key2": "value2" }';

Во входном файле JSON есть строка, которая неправильно экранирована:

const json = '{ "key": "value", "key2": "value2" "key3": "value3" }';

Если у вас появились вопросы про ошибку “Unexpected end of JSON input” в JS, мы будем рады ответить на них в комментариях ниже.

Понравилась статья? Поделить с друзьями:
  • Svhost exe ошибка приложения
  • Syntaxerror return outside function ошибка
  • Syntaxerror positional argument follows keyword argument ошибка
  • Svg 500 ошибка
  • Syntaxerror invalid syntax python ошибка