Unexpected end of json input ошибка

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

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

❌ 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');

  });

“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

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!

Table of Contents

If you are coding in JavaScript, React, or any other JavaScript library/framework, you would have come across the following errors:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

When does this error occur?

This error occurs when you are trying to parse a string to JSON and the string is not parsable.
In other words, it happens when you pass an invalid JSON string to JSON.parse() function.

Try executing the following code in the browser console:

You will see the following error:

json parse error 1

So the error is telling that it is seeing a string < at the beginning since a valid JSON should start with {.

Now if you execute the following code, you will get the second error:

json parse error 2

If you observe the JSON string, it starts as a valid JSON, however, the JSON is not complete. Hence it is telling ‘unexpected end of JSON input’.

Let’s now see how we can reproduce same issue in React application:

App.js

1import { useEffect } from "react"

2

3function App() {

4 useEffect(() => {

5 const fetchData = async () => {

6 const response = await fetch("https://jsonplaceholder.typicode.com/")

7 const data = await response.json()

8 console.log({ data })

9 }

10

11 fetchData()

12 }, [])

13 return <div className="App">home</div>

14}

15

16export default App

The above code attempts to fetch the data from https://jsonplaceholder.typicode.com/ and calls response.json().
When we call response.json(), it internally calls JSON.parse() to convert the response into a JSON Object.

However, the URL we have passed is of an HTML page and we will be getting an HTML string as the response.
Hence, if you execute the above code, it will throw the error: SyntaxError: Unexpected token < in JSON at position 0.

How to fix this issue?

We can fix this issue by making sure that we are calling the right endpoint and we are getting a valid JSON response.

We can do so by opening the URL in the browser and checking the content-type response header:

HTML content type

html content type

JSON content type

If you check the content-type of an endpoint that returns a valid JSON, like https://jsonplaceholder.typicode.com/posts,
you will see the content-type as application/json.

json content type

You could also validate if a string is a valid JSON or not in tools like JSON Formatter.

If you have liked article, stay in touch with me by following me on twitter.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Labels

archived due to age

This issue has been archived; please open a new issue for any further discussion

auto closed

The bot closed this issue

core

Relates to ESLint’s core APIs and features

enhancement

This change enhances an existing feature of ESLint

evaluating

The team will evaluate this issue to decide whether it meets the criteria for inclusion

Comments

@vladshcherbin

The version of ESLint you are using.
6.6.0

The problem you want to solve.
When I have an empty package.json file in nested folder, near checked files, eslint gives error:

Error: Unexpected end of JSON input

There were similar issues previously — #11026 (comment), #7748 and there was no error in 5.16.0. Since 6.0.0 an error is thrown.

Your take on the correct solution to problem.
It would be nice to have an option to disable this error. I tried to ignore this json file, but didn’t succeed.

This is useful for me because I want this file to be invalid on purpose so later I can check it.

Are you willing to submit a pull request to implement this change?
Probably not, no free time to dive in atm.

@vladshcherbin
vladshcherbin

added

core

Relates to ESLint’s core APIs and features

enhancement

This change enhances an existing feature of ESLint

triage

An ESLint team member will look at this issue soon

labels

Nov 14, 2019

@platinumazure

Hi @vladshcherbin, thanks for the issue.

I wonder if that message is being thrown while searching for an ESLint configuration file (or eslintConfig key in package.json)?

Do you have an ESLint configuration file? If not, you should create one by running ESLint with the --init comment line option. That could be a workaround to avoid this error being thrown. (Of course, I could be wrong and it could be something else.)

If you have a stack trace with this error, could you please post it? Thanks!

@kaicataldo

Could you also explain what you mean by «empty package.json«? Does the file literally have nothing in it or does it have {}?

@vladshcherbin

so, in my situation I have a similar structure:

|-- tests
|   |-- bad-json
|   |   |-- index.js
|   |   `-- package.json
|   `-- other-tests
|-- .eslintrc.js
`--  package.json

As you can see, here I have root package.json and .eslintrc.js config, both are valid and working. In tests/bad-json folder I have another package.json file, which is completely empty (not even a {}).

When I try to lint tests folder, I believe eslint tries to read this nested tests/bad-json/package.json file to find eslint configuration and gives me an error.

I tried to add this package.json file to .eslintignore, override.excludedFiles, but didn’t have any luck. I got this error after updating from eslint v5 to v6.

Error screenshot

image

I can also create a small reproduction repo if needed.

@kaicataldo

Thanks for the info! This will make it much easier to debug.

@kaicataldo
kaicataldo

added

evaluating

The team will evaluate this issue to decide whether it meets the criteria for inclusion

and removed

triage

An ESLint team member will look at this issue soon

labels

Nov 15, 2019

@mysticatea

When I try to lint tests folder, I believe eslint tries to read this nested tests/bad-json/package.json file to find eslint configuration and gives me an error.

You are right. In that case, you need /tests/bad-json in your .eslintignore, or a valid ESLint configuration file that has a higher priority than package.json such as /tests/bad-json/.eslintrc.yml.

Because ESLint reads /tests/bad-json/package.json when it entered /tests/bad-json directory in order to check if the config file change how ESLint traverses the subdirectory via RFC20 or RFC22. (so /tests/bad-json/package.json can have a setting that ignores/unignores /tests/bad-json/*.)

@kaicataldo

@mysticatea Do you think it would make sense to ignore empty package.json files, or at least only log a warning but not exit with an error code? Seems like if the package.json file doesn’t have any contents that it clearly is not intended to be used to configure ESLint.

@mysticatea

I feel odd if ESLint handles empty config files in special. A tests/bad-json/package.json may contain invalid JSON. So this is how ESLint handles parsing errors in config files.

The current strategy is to stop at a parsing error in config files. To print a warning and continue sounds good, but I have a concern about arbitrary outputs from outside of configured formatter.

@mysticatea

Honestly, I think reasonable if we going to deprecate config files in subdirectories.

@vladshcherbin

You are right. In that case, you need /tests/bad-json in your .eslintignore, or a valid ESLint configuration file that has a higher priority than package.json such as /tests/bad-json/.eslintrc.yml.

I tried different variants of adding /tests/bad-json to .eslintignore and only 1 variant worked — when I ignore the whole directory. However, I need files inside of this folder to be linted too, for example tests/bad-json/index.js. Some of my tries:

# ignores folder contents
/tests/bad-json

# json error (same with ** or *)
/tests/bad-json/**

# ignores folder contents
/tests/bad-json
!/tests/bad-json/index.js

So, I believe current workaround in my situation is to have a higher priority config file in this folder.

@platinumazure

I think we should treat invalid or empty object package.json the same way as we treat lack of configuration files of any other type. The only thing in package.json that counts as an ESLint configuration is an eslintConfig key and object. Anything else should not matter to ESLint.

I think we should throw if the eslintConfig value is invalid for some reason (e.g., it’s an array or string rather than an object). But, if we can’t even see an eslintConfig key, then there is no configuration for ESLint to look at and we know this for a fact. Throwing on invalid JSON (for package.json) is unnecessarily intrusive, in my opinion.

@mysticatea

If parsing errors happened, it doesn’t know the errors are in eslintConfig or not. This is similar to that core rules cannot work if parsing errors happened.

Hmm, how about the following steps:

  1. Read the content of package.json
  2. Check if the content includes the constant string "eslintConfig" or not. If not, skip parsing.
  3. Parse the content as JSON.

Therefore, if the package.json file doesn’t contain ESLint config, ESLint skips the package.json file.

@kaicataldo

If parsing errors happened, it doesn’t know the errors are in eslintConfig or not.

This is a good point. As I think on this more, I’m of the mind that invalid JSON should still throw, but that if we wanted to ignore completely empty JSON files, that seems like reasonable behavior. As I think about this more, I actually think the new behavior in 6.0.0 makes a lot of sense.

@vladshcherbin Is there a particular reason the files can’t just contain {} to indicate they are empty? Keeping this behavior because some users might be relying on an error being thrown as a TODO/reminder feels out of scope of the tool’s area of responsibility.

@vladshcherbin

@kaicataldo in a plugin I have user can set input package.json file path, if this file has invalid json format (empty), I throw an error. In tests I want to test this case by providing invalid json file myself to see if correct error is thrown.

@kaicataldo

So, to clarify, you want this feature for testing purposes? If so, there are many assertion libraries that include built-in support for testing this, or you can use try/catch or Promises and assert in the catch block or in the rejection callback as well.

@vladshcherbin

@kaelzhang no, I use eslint only for linting, nothing else. When I try to lint tests folder which contains this empty package.json (created for tests) eslint throws an error when sees it and tries to use.

@vladshcherbin

@kaicataldo

Appreciate all the info! I think the suggestion here is the right solution to this. As someone who works on language tooling, I’ve encountered these kinds of issues a lot, and what I tend to see done is to put test fixture files in a test/fixtures directory and ignore the whole directory when linting.

@eslint-deprecated

Unfortunately, it looks like there wasn’t enough interest from the team
or community to implement this change. While we wish we’d be able to
accommodate everyone’s requests, we do need to prioritize. We’ve found
that issues failing to reach accepted status after 21 days tend to
never be accepted, and as such, we close those issues.
This doesn’t mean the idea isn’t interesting or useful, just that it’s
not something the team can commit to.

Thanks for contributing to ESLint and we appreciate your understanding.

Labels

archived due to age

This issue has been archived; please open a new issue for any further discussion

auto closed

The bot closed this issue

core

Relates to ESLint’s core APIs and features

enhancement

This change enhances an existing feature of ESLint

evaluating

The team will evaluate this issue to decide whether it meets the criteria for inclusion

Понравилась статья? Поделить с друзьями:
  • Unexpected end of file php parse error syntax error unexpected
  • Unexpected error runtime explorer
  • Unexpected character after line continuation character python как исправить
  • Unexpected error running liquibase validation failed 1 change sets check sum
  • Unexpected application error rekordbox что делать