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

I need some help with this error:

Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at Object.success (dashboard.js:22)
at fire (jquery-3.3.1.js:3268)
at Object.fireWith [as resolveWith] (jquery-3.3.1.js:3398)
at done (jquery-3.3.1.js:9305)
at XMLHttpRequest. (jquery-3.3.1.js:9548)

I try to transform a string to a json object using JSON.parse() that cause that error.
I am using oracleJet and this is my code:

function DashboardViewModel() {
  
    var self = this;
    self.lineTypeValue = ko.observable('curved');
    var scatterSeries = []; 
    
    $.getJSON( "http://localhost:8080/points", function (data) {
               console.info(data);
               var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';
               console.info(ch);
               console.info(JSON.parse(scatterSeries));
               scatterSeries.push(JSON.parse(ch));
               
        });
    
    
    /* chart data */
    
    this.scatterSeriesValue = ko.observableArray(scatterSeries);
    
    self.lineTypeOptions = [
        {id: 'straight', label: 'straight'},
        {id: 'curved', label: 'curved'},
        {id: 'stepped', label: 'stepped'},
        {id: 'segmented', label: 'segmented'},
        {id: 'none', label: 'none'}
    ];
  
  
}

The Json that I get from «http://localhost:8080/points» look like this:

{ "results":[  
  [  
     {  
        "b":"0.110547334",
        "cost":"0.000000",
        "w":"1.998889"
     }
  ],
  [  
     {  
        "x":0,
        "y":0
     },
     {  
        "x":1,
        "y":2
     },
     {  
        "x":2,
        "y":4
     },
     {  
        "x":3,
        "y":6
     },
     {  
        "x":4,
        "y":8
     },
     {  
        "x":5,
        "y":10
     },
     {  
        "x":6,
        "y":12
     },
     {  
        "x":7,
        "y":14
     },
     {  
        "x":8,
        "y":16
     },
     {  
        "x":9,
        "y":18
     },
     {  
        "x":10,
        "y":20
     },
     {  
        "x":11,
        "y":22
     },
     {  
        "x":12,
        "y":24
     },
     {  
        "x":13,
        "y":26
     },
     {  
        "x":14,
        "y":28
     },
     {  
        "x":15,
        "y":30
     },
     {  
        "x":16,
        "y":32
     },
     {  
        "x":17,
        "y":34
     },
     {  
        "x":18,
        "y":36
     },
     {  
        "x":19,
        "y":38
     },
     {  
        "x":20,
        "y":40
     },
     {  
        "x":21,
        "y":42
     },
     {  
        "x":22,
        "y":44
     },
     {  
        "x":23,
        "y":46
     },
     {  
        "x":24,
        "y":48
     },
     {  
        "x":25,
        "y":50
     },
     {  
        "x":26,
        "y":52
     },
     {  
        "x":27,
        "y":54
     },
     {  
        "x":28,
        "y":56
     },
     {  
        "x":29,
        "y":58
     },
     {  
        "x":30,
        "y":60
     },
     {  
        "x":31,
        "y":62
     },
     {  
        "x":32,
        "y":64
     },
     {  
        "x":33,
        "y":66
     },
     {  
        "x":34,
        "y":68
     },
     {  
        "x":35,
        "y":70
     },
     {  
        "x":36,
        "y":72
     },
     {  
        "x":37,
        "y":74
     },
     {  
        "x":38,
        "y":76
     },
     {  
        "x":39,
        "y":78
     },
     {  
        "x":40,
        "y":80
     },
     {  
        "x":41,
        "y":82
     },
     {  
        "x":42,
        "y":84
     },
     {  
        "x":43,
        "y":86
     },
     {  
        "x":44,
        "y":88
     },
     {  
        "x":45,
        "y":90
     },
     {  
        "x":46,
        "y":92
     },
     {  
        "x":47,
        "y":94
     },
     {  
        "x":48,
        "y":96
     },
     {  
        "x":49,
        "y":98
     },
     {  
        "x":50,
        "y":100
     },
     {  
        "x":51,
        "y":102
     },
     {  
        "x":52,
        "y":104
     },
     {  
        "x":53,
        "y":106
     },
     {  
        "x":54,
        "y":108
     },
     {  
        "x":55,
        "y":110
     },
     {  
        "x":56,
        "y":112
     },
     {  
        "x":57,
        "y":114
     },
     {  
        "x":58,
        "y":116
     },
     {  
        "x":59,
        "y":118
     },
     {  
        "x":60,
        "y":120
     },
     {  
        "x":61,
        "y":122
     },
     {  
        "x":62,
        "y":124
     },
     {  
        "x":63,
        "y":126
     },
     {  
        "x":64,
        "y":128
     },
     {  
        "x":65,
        "y":130
     },
     {  
        "x":66,
        "y":132
     },
     {  
        "x":67,
        "y":134
     },
     {  
        "x":68,
        "y":136
     },
     {  
        "x":69,
        "y":138
     },
     {  
        "x":70,
        "y":140
     },
     {  
        "x":71,
        "y":142
     },
     {  
        "x":72,
        "y":144
     },
     {  
        "x":73,
        "y":146
     },
     {  
        "x":74,
        "y":148
     },
     {  
        "x":75,
        "y":150
     },
     {  
        "x":76,
        "y":152
     },
     {  
        "x":77,
        "y":154
     },
     {  
        "x":78,
        "y":156
     },
     {  
        "x":79,
        "y":158
     },
     {  
        "x":80,
        "y":160
     },
     {  
        "x":81,
        "y":162
     },
     {  
        "x":82,
        "y":164
     },
     {  
        "x":83,
        "y":166
     },
     {  
        "x":84,
        "y":168
     },
     {  
        "x":85,
        "y":170
     },
     {  
        "x":86,
        "y":172
     },
     {  
        "x":87,
        "y":174
     },
     {  
        "x":88,
        "y":176
     },
     {  
        "x":89,
        "y":178
     },
     {  
        "x":90,
        "y":180
     },
     {  
        "x":91,
        "y":182
     },
     {  
        "x":92,
        "y":184
     },
     {  
        "x":93,
        "y":186
     },
     {  
        "x":94,
        "y":188
     },
     {  
        "x":95,
        "y":190
     },
     {  
        "x":96,
        "y":192
     },
     {  
        "x":97,
        "y":194
     },
     {  
        "x":98,
        "y":196
     },
     {  
        "x":99,
        "y":198
     }
  ]]}

and what I want the variable scatterSeries to hold is a table like this one:

[  {  
  name:"graphe1",
  items:[  
     {  
        x:8,
        y:2
     },
     {  
        x:15,
        y:15
     },
     {  
        x:25,
        y:26
     },
     {  
        x:33,
        y:22
     },
     {  
        x:36,
        y:40
     }
  ]},]

what I get in the console about the string ch is this:

{"name":"graphe1","items":[{"x":0,"y":0},{"x":1,"y":2},{"x":2,"y":4},{"x":3,"y":6},{"x":4,"y":8},{"x":5,"y":10},{"x":6,"y":12},{"x":7,"y":14},{"x":8,"y":16},{"x":9,"y":18},{"x":10,"y":20},{"x":11,"y":22},{"x":12,"y":24},{"x":13,"y":26},{"x":14,"y":28},{"x":15,"y":30},{"x":16,"y":32},{"x":17,"y":34},{"x":18,"y":36},{"x":19,"y":38},{"x":20,"y":40},{"x":21,"y":42},{"x":22,"y":44},{"x":23,"y":46},{"x":24,"y":48},{"x":25,"y":50},{"x":26,"y":52},{"x":27,"y":54},{"x":28,"y":56},{"x":29,"y":58},{"x":30,"y":60},{"x":31,"y":62},{"x":32,"y":64},{"x":33,"y":66},{"x":34,"y":68},{"x":35,"y":70},{"x":36,"y":72},{"x":37,"y":74},{"x":38,"y":76},{"x":39,"y":78},{"x":40,"y":80},{"x":41,"y":82},{"x":42,"y":84},{"x":43,"y":86},{"x":44,"y":88},{"x":45,"y":90},{"x":46,"y":92},{"x":47,"y":94},{"x":48,"y":96},{"x":49,"y":98},{"x":50,"y":100},{"x":51,"y":102},{"x":52,"y":104},{"x":53,"y":106},{"x":54,"y":108},{"x":55,"y":110},{"x":56,"y":112},{"x":57,"y":114},{"x":58,"y":116},{"x":59,"y":118},{"x":60,"y":120},{"x":61,"y":122},{"x":62,"y":124},{"x":63,"y":126},{"x":64,"y":128},{"x":65,"y":130},{"x":66,"y":132},{"x":67,"y":134},{"x":68,"y":136},{"x":69,"y":138},{"x":70,"y":140},{"x":71,"y":142},{"x":72,"y":144},{"x":73,"y":146},{"x":74,"y":148},{"x":75,"y":150},{"x":76,"y":152},{"x":77,"y":154},{"x":78,"y":156},{"x":79,"y":158},{"x":80,"y":160},{"x":81,"y":162},{"x":82,"y":164},{"x":83,"y":166},{"x":84,"y":168},{"x":85,"y":170},{"x":86,"y":172},{"x":87,"y":174},{"x":88,"y":176},{"x":89,"y":178},{"x":90,"y":180},{"x":91,"y":182},{"x":92,"y":184},{"x":93,"y":186},{"x":94,"y":188},{"x":95,"y":190},{"x":96,"y":192},{"x":97,"y":194},{"x":98,"y":196},{"x":99,"y":198}]}

Any help please?!! :( :(

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

The “Unexpected end of JSON input” error is a syntax error that occurs when the JSON you’re trying to parse is incomplete or invalid.

This error typically occurs when you’re trying to parse JSON using the JSON.parse() method, and the JSON string you’re passing to it is either incomplete or invalid. For example, if you’re trying to parse the following JSON:

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

You would get the “Unexpected end of JSON input” error because the JSON is missing a comma between the "name" and "age" properties.

The correct JSON would be:

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

So, one of the things you need to do is to ensure that the JSON you’re trying to parse is complete and valid. You can use a JSON linter or a JSON validator to check if your JSON is correct and fix any syntax errors.

When localStorage is full

If the local storage is full or if there is some other problem when trying to save the JSON string, the localStorage.setItem method will also throw the error.

This can also happen if another application already uses the key you’re trying to parse, and cannot be overwritten.

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

In this case, you could add a try/catch block to the saveUserData function and use console.log to print the error message to the console, like this:

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

With this change, when the saveUserData function is called, it will attempt to save the user object to the local storage. If there is an error, the catch block will be executed and the error message will be printed to the console.


If it helps, here are some examples of syntax errors that will also throw the error.

The JSON input is not properly formatted:

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

The JSON input contains a syntax error:

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

The JSON input has a missing or extra comma:

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

The JSON input has a missing or extra curly brace:

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

The JSON input has a missing or extra square bracket:

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

The JSON input has a missing or extra quotation mark:

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

The JSON input has a string that is not properly escaped:

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

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

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

  });

Понравилась статья? Поделить с друзьями:
  • Syndicate ошибка при запуске приложения 0xc0000142
  • Syndicate 2012 ошибка при запуске 0xc0000142
  • Sync error detected ошибка soulstorm
  • Synaptics wbdi sgx windows 10 lenovo код ошибки 10
  • Synaptics input synaptics ps 2 port touchpad ошибка 0x800f0100