JSON.parse unexpected character in JavaScript

SyntaxError: JSON.parse: bad parsing Breaking Your Code? Your JSON is Invalid

A refresher on the purpose and syntax of JSON, as well as a detailed exploration of the JSON Parse SyntaxError in JavaScript.

Traveling deftly through to the next item in our JavaScript Error Handling series, today we’re taking a hard look at the JSON Parse error. The JSON Parse error, as the name implies, surfaces when using the JSON.parse() method that fails to pass valid JSON as an argument.

In this article, we’ll dig deeper into where JSON Parse errors sit in the JavaScript error hierarchy, as well as when it might appear and how to handle it when it does. Let’s get started!

The Technical Rundown

  • All JavaScript error objects are descendants of the Error object, or an inherited object therein.
  • The SyntaxError object is inherited from the Error object.
  • The JSON Parse error is a specific type of SyntaxError object.

When Should You Use It?

While most developers are probably intimately familiar with JSON and the proper formatting syntax it requires, it doesn’t hurt to briefly review it ourselves, to better understand some common causes of the JSON Parse error in JavaScript.

JavaScript Object Notation, better known as JSON, is a human-readable text format, commonly used to transfer data across the web. The basic structure of JSON consists of objects, which are sets of string: value pairs surrounded by curly braces:




An array is a set of values, surrounded by brackets:




A value can be a string, number, object, array, boolean, or null.

That’s really all there is to the JSON syntax. Since values can be other objects or arrays, JSON can be infinitely nested (theoretically).

In JavaScript, when passing JSON to the JSON.parse() method, the method expects properly formatted JSON as the first argument. When it detects invalid JSON, it throws a JSON Parse error.

For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array or object value set. Notice in the first few examples above, we only use a comma to literally separate values from one another. Here we’ll try adding an extra, or “hanging”, comma after our final value:



Note: We’re using the backtick (`) string syntax to initialize our JSON, which just allows us to present it in a more readable form. Functionally, this is identical to a string that is contained on a single line.

As expected, our extraneous comma at the end throws a JSON Parse error:


Another common syntax issue is neglecting to surround string values within string: value pairs with quotations ("). Many other language syntaxes use similar key: value pairings to indicate named arguments and the like, so developers may find it easy to forget that JSON requires the string to be explicitly indicated using quotation marks:



Here we forgot quotations around the "last" key string, so we get another JSON Parse error:


A few examples are probably sufficient to see how the JSON Parse error comes about, but as it so happens, there are dozens of possible versions of this error, depending on how JSON was improperly formatted. Here’s the full list:

To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.

An Easier Way to Find JavaScript Errors

The first way to find a JSON Parse error is to go through your logs, but when you’re dealing with hundreds, if not thousands, of lines of code, it can be difficult to find that one line of broken code. With Airbrake Error and Performance Monitoring, you can skip the logs and go straight to the line of broken code resulting in the JSON Parse error.

Don’t have Airbrake? Create your free Airbrake dev account today!

Try Airbrake, Create a Free Dev Account

The JavaScript exceptions thrown by JSON.parse() occur when string failed
to be parsed as JSON.

Message

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

Error type

What went wrong?

JSON.parse() parses a string as JSON. This string has to be valid JSON
and will throw this error if incorrect syntax was encountered.

Читайте также:  Код ошибки 0x800c0006 при установке Microsoft Net Framework 4 Windows 7 x64

Examples

JSON.parse() does not allow trailing commas

Both lines will throw a SyntaxError:



// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

Omit the trailing commas to parse the JSON correctly:



Property names must be double-quoted strings

You cannot use single-quotes around properties, like ‘foo’.


// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data

Instead write “foo”:


Leading zeros and decimal points


// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data


// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data

Instead write just 1 without a zero and use at least one digit after a decimal point:



See also


Сообщение

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

Тип ошибки

Что пошло не так?

JSON.parse() обрабатывает (парсит) строку в формате JSON. Это строка должна соответствовать формату, иначе будет выведена ошибка, что был нарушен синтаксис.

Examples

JSON.parse() не допускает запятые

Метод JSON.parse() не разрешает использование, так называемых, trailling запятых.

Обе строки выдадут ошибку типа SyntaxError:



// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

Необходимо убрать последние запятые в строках и тогда ошибки не будет:



Названия свойств должны быть в двойных кавычках

Вы не можете использовать одинарные кавычки в именах свойств. Например, ‘foo’.


// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data

Вместо этого необходимо написать “foo”:


Незначащие нули или плавающая точка без последующей цифры

Вы не можете использовать незначащие нули, например, 01. Плавающая точка должна всегда сопровождаться хотя бы одной цифрой после неё.


// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data


// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data

Вместо этого напишите просто 1 без нуля и используйте хотя бы одну цифру после точки:



Смотрите также

JSON. parse unexpected character in JavaScript

The “SyntaxError: JSON.parse: unexpected character” error occurs when passing
a value that is not a valid JSON string to the JSON.parse method, e.g. a
native JavaScript object.

To solve the error, make sure to only pass valid JSON strings to the
JSON.parse method.

syntaxerror json parse unexpected character

Here is an example of when the error occurs:

// ⛔️ Uncaught SyntaxError: JSON.parse: unexpected character at
// line 1 column 2 of the JSON data


// ⛔️ (if using jQuery)
$

We passed a native JavaScript object to the
JSON.parse method.

If the value is already a native JavaScript value (not JSON), you don’t have to use the JSON.parse or $.parseJSON methods. You can use the value in your code as is.

# Use the JSON. stringify() method if you need to convert a value to JSON

If you’re trying to convert a value to JSON, you should use the
JSON.stringify() method.

// ✅ is now valid JSON string
 json  name 

json 

The JSON.stringify() method converts a native JavaScript value to a JSON
string.

# Make sure the value you are trying to parse is valid JSON

If the value is JSON, then it must be of type string.

  // 👉️ "object"
  // 👉️ "string"
 
   result  
  err 
  // ⛔️ Uncaught SyntaxError: JSON.parse: unexpected character at
  // line 1 column 2 of the JSON data
  err

You can handle the error in the catch function as you see fit.

Читайте также:  Ошибка при установке ISDone.dll

# Convert values to a JSON string before adding them to local storage

If you use local storage to get the value you’re parsing, open your browser’s
console and clear the local storage as it sometimes glitches.

localStorage.clear

Now refresh the page and see if things work as expected.

When using local storage and trying to parse a JSON value, make sure you’re writing a JSON value to local storage.

If the value is not already JSON, you have to pass it to the JSON.stringify
method.

 obj  country 

// 👇️ Store a JSON value in local storage
 obj

// 👇️ parse the value when accessing it
 result  
result 

We used the JSON.stringify() method to convert the object to a JSON string
before adding it to local storage.

We then used the JSON.parse() method to parse the JSON string into a native
JavaScript value.

# Make sure your server sends a valid JSON response

If you are expecting valid JSON from your server, you can console.log the
response from your server and its type using the typeof operator.

If your server doesn’t send a valid JSON response, make sure to set the
Content-Type header to application/json on your server side.

You can also use an online JSON validator to check if a JSON string is valid.

The validator should identify any errors in your JSON string.

If the value is malformed or not valid JSON, you have to format it correctly
before passing it to the JSON.parse method.

# Unexpected end of JSON input Error in JavaScript

The “Unexpected end of JSON input” error occurs when trying to parse invalid
JSON using the JSON.parse or $.parseJSON methods.

Trying to parse a value such as an empty array or a string causes the error.

To solve the error, make sure that the JSON is valid before parsing it.

unexpected end of json input error

Notice that the screenshot shows the line where the error occurred. In the
example, the error occurred in the index.js file on line 3.

// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input


// ⛔️ Uncaught SyntaxError:

We passed an empty array and an empty string to the JSON.parse method and got
the error.

The same would be the result if you were using the $.parseJSON method.

// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input
$

We got the error because we are trying to parse invalid JSON.

# Converting a JavaScript value to a JSON string

If you’re trying to convert a JavaScript value to a JSON string, use the
JSON.stringify() method instead.

 arr    

// ✅ Convert JavaScript value to JSON string
 jsonStr  arr


jsonStr

// 👇️ string
 jsonStr

The JSON.stringify method converts a
JavaScript value to a JSON string.

# Your server might be sending an empty response

The error also occurs if you try to parse an empty response from the server, or
when your server doesn’t send the correct CORS headers along with the response.

If your server sends an empty response and you try to JSON.parse() it, you
will get an error. In this case, you should remove the parsing logic.

If you’re getting the value from your server, make sure the server is setting
the Content-Type header to application/json.

  • Wrap your parsing logic in a try/catch block.
  • Make sure to return a valid JSON response from your server.
  • Remove the parsing logic from your code if you are expecting an empty server
    response.

You can inspect the response of your server by opening your developer tools
(F12) and clicking on your Network tab. If you click on the Response tab,
you will see the server’s response.

browser network tab response

# Using a try/catch statement to handle the error

 
   result  
  result
  err 
  // 👇️ SyntaxError: Unexpected end of JSON input
   err

If the JSON.parse method throws an error due to parsing invalid JSON, the
error is passed as a parameter to the catch method where we can handle it.

# Removing the call to JSON. parse() or validating your JSON

Alternatively, you can remove the call to the JSON.parse method if you know
the server’s response doesn’t contain valid JSON.

When working with JSON data, make sure:

  1. To use double quotes to wrap your property names and string values.
// ✅ uses double quotes
 jsonStr  

 result  jsonStr
result 
  1. You don’t have any missing colons or commas.
// ⛔️ has a missing comma after "id": 1
 jsonStr  
  1. All of the square brackets, curly braces and quotation marks are closed.
// ⛔️ quotation mark of `id` is not closed
 jsonStr  
  1. You don’t have any trailing commas.
// ⛔️ has a trailing comma after "name": "Alice",
 jsonStr  

Remove the trailing comma to resolve the issue.

  1. You haven’t forgotten to wrap multiple objects into an array using square
    brackets [].
 jsonStr  

// ⛔️ SyntaxError: Unexpected non-whitespace character after JSON at position 33
jsonStr

The issue in the code sample above is that we have multiple objects that are not
wrapped in an array.

// ✅ wrapped objects in square brackets
 jsonStr  


jsonStr

The same applies when writing JSON in a file that has a .json extension.


   
   


   
   

end of file expected json

Wrapping the objects in an array solves the error.


  
     
     
  
  
     
     
  

  1. Make sure you don’t have trailing symbols after closing the JSON object or
    array.

   
   

asdf

The code sample causes the End of file expected. json error because of the
asdf text after the object.

Читайте также:  Ошибка установки параметра шифрования

end of file expected json because of trailing symbols

To resolve the issue, make sure to remove any trailing symbols after your JSON
object or array.


   
   

  1. Make sure you don’t have duplicate keys in JSON objects.

   
   
   

The code sample causes the “Duplicate json key json” issue because the id key
exists twice in the same object.

To resolve the issue, make sure to remove any duplicate keys.


   
   

You can also use an online JSON validator to check if a JSON string is valid.

The JSON.parse method parses a JSON string
into a native JavaScript value.

 jsonStr  

// ✅ parse JSON string into JS value
 result  jsonStr
result 

// ✅ convert JS value to JSON string
 jsonStr2  id  name 
jsonStr2 

The JSON.stringify method converts a
native JavaScript value to a JSON string.


   
   


   
   
       


   
   
          


  
     
     
  
  
     
     
  

“undefined” is not valid JSON in JS [Solved]

The “SyntaxError: “undefined” is not valid JSON” error occurs when we pass a
value that is not valid JSON to the JSON.parse or $.parseJSON methods.

To solve the error, inspect the value you’re trying to parse and make sure
it’s a valid JSON string before parsing it.

syntaxerror-undefined-is-not-valid-json

You might also get the error named as “Unexpected token u in JSON at position
0 at JSON.parse”
depending on your browser or version of Node.js.

SyntaxError:  is not valid JSON

Uncaught SyntaxError: Unexpected token u  JSON at position 
  at JSON.parseanonymous
    at index.js:3

syntaxerror unexpected token u in json at position 0

Here’s an example of how the error occurs.

// ⛔️ Uncaught SyntaxError: "undefined" is not valid JSON
// Unexpected token u in JSON at position 0 at JSON.parse


// ⛔️ Uncaught SyntaxError: "undefined" is not valid JSON
// Unexpected token u in JSON at position 0 at JSON.parse
$

When an undefined value is passed to the
JSON.parse method:

  1. It gets converted to a string.
  2. The JSON.parse() method attempts to parse the string.
  3. The method fails at parsing the string and throws an error.

# Common reasons the error occurs

There are multiple reasons the “Unexpected token u in JSON at position 0” error
occurs when calling JSON.parse:

  1. Referencing a non-existent property on an object.
 obj  name 

// ⛔️ trying to parse an undefined property on an object
obj
  1. Your server or local storage call is returning an empty response.
  2. Forgetting to convert a value to JSON before storing it in local storage.
  3. You are fetching data immediately as the page loads and causing a race
    condition.

# Wrap the JSON. parse call in a try/except block

To make sure you handle the error, put the JSON.parse call in a try/catch
statement.

 value  

 
   result  value
  result
  err 
  // 👇️ This runs
   err

# All JSON values must be of type string

All JSON values must be of type string. Not all strings are valid JSON, but
all JSON values have a type of string.

You can use the typeof operator to check the type of a value.

  // 👉️ undefined
  // 👉️ object

// 👇️ string
 name 

The typeof operator indicates the type of a value.

# Clear the local storage in your browser’s console

If you use local storage, open your browser’s console and clear the local
storage as it sometimes glitches.

localStorage.clear

clear your local storage

Now refresh the page and see if things work as expected.

When using local storage and trying to parse a JSON value, make sure you’re writing a JSON value to local storage.

# Convert the value to JSON before writing it to local storage

If the value isn’t already JSON, you have to pass it to the JSON.stringify()
method before writing it to local storage.

 obj  name 

// 👇️ Store a JSON value in local storage
 obj

// 👇️ parse the value when accessing it
 result  
result 

We convert the object to a JSON string and store the JSON string as a key on the
localStorage object.

You have to do the same when working with arrays.

 arr    

// 👇️ Store a JSON value in local storage
 arr

// 👇️ parse the value when accessing it
 result  
result 

# Wait for the page to load before fetching data

If you’re reading data from a file or fetching data on the server immediately as
the page loads, use window.onload or $(document).ready().

// ✅ using jQuery
  
  $   
    data
  


// ✅ using fetch
    
  
      
       response 
          
      

       response
    
      
      result
    
      err

We make a request to the server after the DOM or window has loaded. This helps
us avoid any race conditions like trying to parse a value before the DOM is
fully loaded.

# Make sure your server sends a valid JSON response

If you’re fetching data from a server, console.log the response you get and
make sure it’s a valid JSON string.

Does your server send a Content-Type header of application/json? Pass the value to an online JSON validator and see if you get any errors.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *