Json parse error on valid json

Json parse error on valid json

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

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 you’re trying to parse a JSON string to a native JavaScript value, you have to make sure the value is valid JSON before parsing it, or you can use a try/catch block to handle any errors.

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

Here’s an example of how to use a try/catch block to handle an eventual error while parsing a JSON value.

We call the JSON.parse method inside of a try/catch block. If the JSON valid is invalid, the method will throw an error which will get passed to the catch() function.

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

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.

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

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

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 JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Try it



The string to parse as JSON. See the JSON object for a description of JSON syntax.

If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:

The key associated with the value.

The value produced by parsing.

Return value

The Object , Array , string, number, boolean, or null value corresponding to the given JSON text .


Thrown if the string to parse is not valid JSON.


JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it’s a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the «__proto__» key — see Object literal syntax vs. JSON.

Читайте также:  Caused by java io ioexception createprocess error 193 1 не является приложением win32

The reviver parameter

If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver .

The reviver is called with the object containing the property being processed as this , and two arguments: key and value , representing the property name as a string (even for arrays) and the property value. If the reviver function returns undefined (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.

Similar to the replacer parameter of JSON.stringify() , reviver will be last called on the root object with an empty string as the key and the root object as the value . For JSON text parsing to primitive values, reviver will be called once.

Note that reviver is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.


SyntaxError: JSON.parse: bad parsing

Deeksha Agarwal

Posted On: April 5, 2018


3 Min Read

  • Home
  • >
  • Blog
  • >
  • SyntaxError: JSON.parse: bad parsing

JSON or JavaScript Object Notation is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However just like any programming language, it throws a lot of errors when it decide that today is not going to be your day.

JSON.Parse Syntax Errors

In most web applications, nearly all data transferred from web server is transmitted in a string format. To convert that string into JSON, we use JSON.parse() function, and this the main function that throws errors. Nearly all JSON.parse errors are a subset of SyntaxError error type. Debugging console throws around 32 different errors messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data .

Why the SyntaxError Horror?

SyntaxError is an inherited object of the main error object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a “ instead of a ‘ and you invite to face the SyntaxError JSON.parse: unexpected character .

Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, i forgot to remove a trailing comma




Base type¶

All exceptions inherit from class json::exception (which in turn inherits from std::exception ). It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as «wildcard» to catch exceptions.

Switch off exceptions¶

Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions or by defining the symbol JSON_NOEXCEPTION . In this case, exceptions are replaced by abort() calls. You can further control this behavior by defining JSON_THROW_USER (overriding throw ), JSON_TRY_USER (overriding try ), and JSON_CATCH_USER (overriding catch ).

Note that JSON_THROW_USER should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.

The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.

Читайте также:  Hamlib error io error while opening connection to rig что делать

Note the explanatory what() string of exceptions is not available for MSVC if exceptions are disabled, see #2824.

Extended diagnostic messages¶

Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult.

This exception can be hard to debug if storing the value «12» and accessing it is further apart.

To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer.

As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS to 1 before including json.hpp .

Now the exception message contains a JSON Pointer /address/housenumber that indicates which value has the wrong type.

Parse errors¶

This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.

Exceptions have ids 1xx.

Member byte holds the byte index of the last read character in the input file.

For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).

The following code shows how a parse_error exception can be caught.


This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position.

Input ended prematurely:

Control character was not escaped:

String was not closed:

Invalid number format:

\u was not be followed by four hex digits:

Invalid UTF-8 surrogate pair:

Invalid UTF-8 byte:

  • Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully opened.
  • Paste the input to a JSON validator like http://jsonlint.com or a tool like jq.


JSON uses the \uxxxx format to describe Unicode characters. Code points above 0xFFFF are split into two \uxxxx entries («surrogate pairs»). This error indicates that the surrogate pair is incomplete or contains an invalid code point.

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.


Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.

This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.


RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.


An operation of a JSON Patch document must contain exactly one «op» member, whose value indicates the operation to perform. Its value must be one of «add», «remove», «replace», «move», «copy», or «test»; other values are errors.


An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 0 .


A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.


In a JSON Pointer, only

1 are valid escape sequences.


A JSON Pointer array index must be a number.


When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.


An unexpected byte was read in a binary format or length information is invalid (BSON).


What Is JSON and How to Handle an “Unexpected Token” Error

In this article you will learn what JSON is and how you can deal with errors occurring when parsing JSON data, such as «Unexpected Token

What Is JSON

JSON, which is an acronym for JavaScript Object Notation, is one of the most popular data formats used for transmitting data. It is a lightweight format and consists of name-value pairs. Values can be strings, arrays, or any other data that can be serialized.

Читайте также:  Все прошивки миуи 12

In the old days XML was primarily used for interchanging data, but since JSON appeared it is often used as a replacement of XML. A JSON file should end with the .json extension.

Below you can see an example of a JSON format.

JSON format is quite similar to JavaScript objects, but it is not always the case. It is important to remember that every property name must be wrapped in double quotes.

Unexpected Token JSON.parse() function or use the .json() method on the fetch object, it can result in a JavaScript exception being thrown. But don’t worry, it’s not the end of the world and we can handle it. There can be different causes for this happening so let’s see what we can do about it.

Is My JSON Formatted Correctly?

Projects sometimes require configuration that is sent to the client from a server. Just so you know, storing the config details as a JSON will be faster than using an object literal, as engines need to do more steps when running an object literal than JSON.parse() , for instance. The performance comparison of JSON vs JavaScript is not a topic of this article so it will not be covered, but if you are interested, then you can read more about it here.

Introduction to JSON Web Tokens (JWT)

JSON Web Tokens are a useful tool and a better way of implementing authorization in web applications, but what exactly are they and how do they work?

If you have a file with JSON data, one of the first things to do is to ensure that the data is formatted correctly. There are a few sites that can help you with that. These formatters not only will check if your JSON is formatted correctly, but they can also fix some of the errors, beautify it, or make it compact.

To be honest, one of the mistakes I am often guilty of myself is using single quotes instead of double quotes. The image below shows how a format checker can make your life easier.

If your JSON is formatted correctly, then it is time to check what else could be wrong.

My JSON is Formatted Correctly—What Next?

“Unexpected token fetch function is used for sending an API request from a client. After receiving a response from a server, usually it is parsed to JSON.

The first thing to do in this situation is to confirm where the error is happening exactly. To ensure the error happens on the exact line we think it does, we can wrap the JSON parsing code in a try-catch block. Check the code below.

If this is the culprit, then it will be clearly visible in the developer tools console, as “Error happened here!” will be displayed. Otherwise, you might need to look for it somewhere else. A good idea is to sometimes comment out code piece by piece to see when an error stops being thrown. You can also use an early return statement.

The next step is to check if the data we are expecting to see is actually being sent from the server. As shown on the image below, head to the “Network” tab in DevTools, find the request, and click on the “Response” tab.

In this example, we can see a JSON string sent from the swapi API, so it is correct. However, in a different case, the response could be in the XML format or the server could have sent an HTML file. The former could happen if you are dealing with a server that can return different responses depending on the content-type header provided. If this is the case, when you send a request, make sure you specify the content-type header as shown below: