JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.
Why do we get JSON parse error?
Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
How to handle JSON parse error?
There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.
1. Using try-catch block
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
try {
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
} catch (e) {
console.log(e);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
}
2. Using if-else block
Another way to handle JSON parse error is using if-else block.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
console.log(obj);
// expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
}
3. Using try-catch block with JSON.parse()
The third way to handle JSON parse error is using try-catch block with JSON.parse().
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
4. Using try-catch block with JSON.parse() and JSON.stringify()
The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}
Overview¶
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.
Example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>
#define JSON_TRY_USER if(true)
#define JSON_CATCH_USER(exception) if(false)
#define JSON_THROW_USER(exception)
{std::clog << "Error in " << __FILE__ << ":" << __LINE__
<< " (function " << __FUNCTION__ << ") - "
<< (exception).what() << std::endl;
std::abort();}
#include <nlohmann/json.hpp>
Note the explanatory what()
string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
See documentation of JSON_TRY_USER
, JSON_CATCH_USER
and JSON_THROW_USER
for more information.
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.
Example
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (json::exception& e)
{
std::cout << e.what() << 'n';
}
}
Output:
[json.exception.type_error.302] type must be number, but is string
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
.
Example
#include <iostream>
# define JSON_DIAGNOSTICS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (json::exception& e)
{
std::cout << e.what() << 'n';
}
}
Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string
Now the exception message contains a JSON Pointer /address/housenumber
that indicates which value has the wrong type.
See documentation of JSON_DIAGNOSTICS
for more information.
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.
Byte index
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).
Example
The following code shows how a parse_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// parsing input with a syntax error
json::parse("[1,2,3,]");
}
catch (json::parse_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << 'n'
<< "byte position of error: " << e.byte << std::endl;
}
}
Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal
exception id: 101
byte position of error: 8
json.exception.parse_error.101¶
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.
Example message
Input ended prematurely:
[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal
No input:
[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal
Control character was not escaped:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to u0009 or \; last read: '"<U+0009>'"
String was not closed:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '"'
Invalid number format:
[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'
u
was not be followed by four hex digits:
[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: 'u' must be followed by 4 hex digits; last read: '"u01"'
Invalid UTF-8 surrogate pair:
[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '"uD7FFuDC00'"
Invalid UTF-8 byte:
[json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '"vous 352t'
Tip
- 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.exception.parse_error.102¶
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.
Example message
parse error at 14: missing or wrong low surrogate
Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
json.exception.parse_error.103¶
Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
Example message
parse error: code points above 0x10FFFF are invalid
Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
json.exception.parse_error.104¶
RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.
Example message
[json.exception.parse_error.104] parse error: JSON patch must be an array of objects
json.exception.parse_error.105¶
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.
Example message
[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'
[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'
[json.exception.parse_error.105] parse error: operation value 'foo' is invalid
json.exception.parse_error.106¶
An array index in a JSON Pointer (RFC 6901) may be 0
or any number without a leading 0
.
Example message
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
json.exception.parse_error.107¶
A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a /
character.
Example message
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'
json.exception.parse_error.108¶
In a JSON Pointer, only ~0
and ~1
are valid escape sequences.
Example message
[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'
json.exception.parse_error.109¶
A JSON Pointer array index must be a number.
Example messages
[json.exception.parse_error.109] parse error: array index 'one' is not a number
[json.exception.parse_error.109] parse error: array index '+1' is not a number
json.exception.parse_error.110¶
When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
Example message
[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input
[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A
json.exception.parse_error.112¶
An unexpected byte was read in a binary format or length information is invalid (BSON).
Example messages
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02
[json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648
[json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1
json.exception.parse_error.113¶
While parsing a map key, a value that is not a string has been read.
Example messages
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82
json.exception.parse_error.114¶
The parsing of the corresponding BSON record type is not implemented (yet).
Example message
[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF
json.exception.parse_error.115¶
A UBJSON high-precision number could not be parsed.
Example message
[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A
Iterator errors¶
This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx.
Example
The following code shows how an invalid_iterator
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling iterator::key() on non-object iterator
json j = "string";
json::iterator it = j.begin();
auto k = it.key();
}
catch (json::invalid_iterator& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators
exception id: 207
json.exception.invalid_iterator.201¶
The iterators passed to constructor basic_json(InputIT first, InputIT last)
are not compatible, meaning they do not belong to the same container. Therefore, the range (first
, last
) is invalid.
Example message
[json.exception.invalid_iterator.201] iterators are not compatible
json.exception.invalid_iterator.202¶
In the erase or insert function, the passed iterator pos
does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
Example messages
[json.exception.invalid_iterator.202] iterator does not fit current value
[json.exception.invalid_iterator.202] iterators first and last must point to objects
json.exception.invalid_iterator.203¶
Either iterator passed to function erase(IteratorType first, IteratorType last
) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
Example message
[json.exception.invalid_iterator.203] iterators do not fit current value
json.exception.invalid_iterator.204¶
When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (begin(),
end()),
because this is the only way the single stored value is expressed. All other ranges are invalid.
Example message
[json.exception.invalid_iterator.204] iterators out of range
json.exception.invalid_iterator.205¶
When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin()
iterator, because it is the only way to address the stored value. All other iterators are invalid.
Example message
[json.exception.invalid_iterator.205] iterator out of range
json.exception.invalid_iterator.206¶
The iterators passed to constructor basic_json(InputIT first, InputIT last)
belong to a JSON null value and hence to not define a valid range.
Example message
[json.exception.invalid_iterator.206] cannot construct with iterators from null
json.exception.invalid_iterator.207¶
The key()
member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
Example message
[json.exception.invalid_iterator.207] cannot use key() for non-object iterators
json.exception.invalid_iterator.208¶
The operator[]
to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.208] cannot use operator[] for object iterators
json.exception.invalid_iterator.209¶
The offset operators (+
, -
, +=
, -=
) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.209] cannot use offsets with object iterators
json.exception.invalid_iterator.210¶
The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first
, last
) is invalid.
Example message
[json.exception.invalid_iterator.210] iterators do not fit
json.exception.invalid_iterator.211¶
The iterator range passed to the insert function must not be a subrange of the container to insert to.
Example message
[json.exception.invalid_iterator.211] passed iterators may not belong to container
json.exception.invalid_iterator.212¶
When two iterators are compared, they must belong to the same container.
Example message
[json.exception.invalid_iterator.212] cannot compare iterators of different containers
json.exception.invalid_iterator.213¶
The order of object iterators cannot be compared, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.213] cannot compare order of object iterators
json.exception.invalid_iterator.214¶
Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin()
.
Example message
[json.exception.invalid_iterator.214] cannot get value
Type errors¶
This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
Example
The following code shows how a type_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling push_back() on a string value
json j = "string";
j.push_back("another string");
}
catch (json::type_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.type_error.308] cannot use push_back() with string
exception id: 308
json.exception.type_error.301¶
To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
Example message
[json.exception.type_error.301] cannot create object from initializer list
json.exception.type_error.302¶
During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
Example messages
[json.exception.type_error.302] type must be object, but is null
[json.exception.type_error.302] type must be string, but is object
json.exception.type_error.303¶
To retrieve a reference to a value stored in a basic_json
object with get_ref
, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType
must be array_t &
.
Example messages
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number"
json.exception.type_error.304¶
The at()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.304] cannot use at() with string
[json.exception.type_error.304] cannot use at() with number
json.exception.type_error.305¶
The operator[]
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.305] cannot use operator[] with a string argument with array
[json.exception.type_error.305] cannot use operator[] with a numeric argument with object
json.exception.type_error.306¶
The value()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.306] cannot use value() with number
json.exception.type_error.307¶
The erase()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.307] cannot use erase() with string
json.exception.type_error.308¶
The push_back()
and operator+=
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.308] cannot use push_back() with string
json.exception.type_error.309¶
The insert()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.309] cannot use insert() with array
[json.exception.type_error.309] cannot use insert() with number
json.exception.type_error.310¶
The swap()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.310] cannot use swap() with number
json.exception.type_error.311¶
The emplace()
and emplace_back()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.311] cannot use emplace() with number
[json.exception.type_error.311] cannot use emplace_back() with number
json.exception.type_error.312¶
The update()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.312] cannot use update() with array
json.exception.type_error.313¶
The unflatten
function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined.
Example message
[json.exception.type_error.313] invalid value to unflatten
json.exception.type_error.314¶
The unflatten
function only works for an object whose keys are JSON Pointers.
Example message
Calling unflatten()
on an array [1,2,3]
:
[json.exception.type_error.314] only objects can be unflattened
json.exception.type_error.315¶
The unflatten()
function only works for an object whose keys are JSON Pointers and whose values are primitive.
Example message
Calling unflatten()
on an object {"/1", [1,2,3]}
:
[json.exception.type_error.315] values in object must be primitive
json.exception.type_error.316¶
The dump()
function only works with UTF-8 encoded strings; that is, if you assign a std::string
to a JSON value, make sure it is UTF-8 encoded.
Example message
Calling dump()
on a JSON value containing an ISO 8859-1 encoded string:
[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F
Tip
- Store the source file with UTF-8 encoding.
- Pass an error handler as last parameter to the
dump()
function to avoid this exception:json::error_handler_t::replace
will replace invalid bytes sequences withU+FFFD
json::error_handler_t::ignore
will silently ignore invalid byte sequences
json.exception.type_error.317¶
The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true
or null
JSON object cannot be serialized to BSON)
Example messages
Serializing null
to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null
Serializing [1,2,3]
to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array
Tip
Encapsulate the JSON value in an object. That is, instead of serializing true
, serialize {"value": true}
Out of range¶
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
Example
The following code shows how an out_of_range
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling at() for an invalid index
json j = {1, 2, 3, 4};
j.at(4) = 10;
}
catch (json::out_of_range& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.out_of_range.401] array index 4 is out of range
exception id: 401
json.exception.out_of_range.401¶
The provided array index i
is larger than size-1
.
Example message
array index 3 is out of range
json.exception.out_of_range.402¶
The special array index -
in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
Example message
array index '-' (3) is out of range
json.exception.out_of_range.403¶
The provided key was not found in the JSON object.
json.exception.out_of_range.404¶
A reference token in a JSON Pointer could not be resolved.
Example message
unresolved reference token 'foo'
json.exception.out_of_range.405¶
The JSON Patch operations ‘remove’ and ‘add’ can not be applied to the root element of the JSON value.
Example message
JSON pointer has no parent
json.exception.out_of_range.406¶
A parsed number could not be stored as without changing it to NaN or INF.
Example message
number overflow parsing '10E1000'
json.exception.out_of_range.407¶
UBJSON and BSON only support integer numbers up to 9223372036854775807.
Example message
number overflow serializing '9223372036854775808'
Note
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
json.exception.out_of_range.408¶
The size (following #
) of an UBJSON array or object exceeds the maximal capacity.
Example message
excessive array size: 8658170730974374167
json.exception.out_of_range.409¶
Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.
Example message
BSON key cannot contain code point U+0000 (at byte 2)
Further exceptions¶
This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx.
Example
The following code shows how an other_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
try
{
// executing a failing JSON Patch operation
json value = R"({
"best_biscuit": {
"name": "Oreo"
}
})"_json;
json patch = R"([{
"op": "test",
"path": "/best_biscuit/name",
"value": "Choco Leibniz"
}])"_json;
value.patch(patch);
}
catch (json::other_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.other_error.501] unsuccessful: {"op":"test","path":"/best_biscuit/name","value":"Choco Leibniz"}
exception id: 501
json.exception.other_error.501¶
A JSON Patch operation ‘test’ failed. The unsuccessful operation is also printed.
Example message
Executing {"op":"test", "path":"/baz", "value":"bar"}
on {"baz": "qux"}
:
[json.exception.other_error.501] unsuccessful: {"op":"test","path":"/baz","value":"bar"}
Last update: December 19, 2022
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 theError
object. - The
JSON Parse
error is a specific type ofSyntaxError
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:
{
"first": "Jane",
"last": "Doe"
}
An array
is a set of values
, surrounded by brackets:
[
"Jane",
"Doe"
]
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
:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
«last»: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
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:
[EXPLICIT] SyntaxError: Unexpected token } in JSON at position 107
In this case, it’s telling us the }
token is unexpected, because the comma at the end informs JSON that there should be a third value
to follow.
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:
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
var json = `
{
«first»: «Jane»,
last: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}
Here we forgot quotations around the "last"
key string
, so we get another JSON Parse
error:
[EXPLICIT] SyntaxError: Unexpected token l in JSON at position 76
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:
JSON Parse Error Messages |
---|
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 |
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!
Note: We published this post in February 2017 and recently updated it in April 2022.
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.
Examples
JSON.parse() does not allow trailing commas
Both lines will throw a SyntaxError:
JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
Omit the trailing commas to parse the JSON correctly:
JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');
Property names must be double-quoted strings
You cannot use single-quotes around properties, like ‘foo’.
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
Instead write «foo»:
JSON.parse('{"foo": 1}');
Leading zeros and decimal points
You cannot use leading zeros, like 01, and decimal points must be followed by at least
one digit.
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data
JSON.parse('{"foo": 1.}');
// 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:
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
See also
The most common reason for this error is attempting JSON to parse an HTML or XML response. The HTML and XML documents start with <, and JSON identifies it as an unparsable string. It is also possible that you are requesting an api that you don’t have permission to access. In that case, you expect a JSON, but the server returns a permission denial HTML.
This article demonstrates several JSON parsing errors with code examples.
Reason for Unexpected token < in JSON error
Listed below is a simple express.js route that generates an HTML response. It can be any api endpoint. The api generates the HTML response <p>This is an HTML response</p>.
router.post("/user/create/html", (request, response) => {
const reply = "<p>This is an HTML response</p>"
response.set('Content-Type', 'text/html');
response.send(reply);
});
Now let’s find out what happens when we try to parse this response with the JSON parser. The code makes a post request to the endpoint that produces an HTML response. Then it tries to JSON parse the response.
const serverHtmlResponse = await axios.post('/user/create/html')
console.log(serverHtmlResponse.headers["content-type"])
console.log(serverHtmlResponse.data)
console.log(typeof serverHtmlResponse.data)
const htmlResponse = JSON.parse(serverHtmlResponse.data)
Note that the endpoint’s response type is text/html and the content is <p>This is an HTML response</p>. The content is not parsable. Thats the reason you see the first character of the content < in the error message.
Reason for Unexpected token o in JSON at position 1
That error happens when we attempt to JSON parse an object.
The below express.js route produces a JSON object as the response.
router.post("/user/create/json", (request, response) => {
const reply = "This is a JSON object response"
response.json({response:reply});
});
The response of this endpoint is {response: ‘This is a JSON object response’}. That is not a JSON string. It is an object. The console.log(typeof serverJsonResponse.data) proves the api response is an object.
const serverJsonResponse = await axios.post('/user/create/json')
console.log(serverJsonResponse.headers["content-type"])
console.log(typeof serverJsonResponse.data)
console.log(serverJsonResponse.data)
const jsonResponse = JSON.parse(serverJsonResponse.data)
Therefore, what happens here is JSON.parse(«[object Object]»)
and JSON complains about the character «o» it encountered first.
How to parse a JSON string correctly?
The JSON.parse() method accepts a string that correctly represents a JSON object. In other words, a string that is parsable into a JSON object.
Below is an express route that produces a JSON string like {«response»:»This is a JSON string response»}.
router.post("/user/create/jsonstring", (request, response) => {
const reply = `{"response":"This is a JSON string response"}`
response.json(reply)
});
The response is application/json, and the type is string. This type of response is parsable with JSON parser as long as the response string can represent a valid object.
const serverResponse = await axios.post('/user/create/jsonstring')
console.log(serverResponse.headers["content-type"])
console.log(typeof serverResponse.data)
console.log(serverResponse.data)
const jsonStringResponse = JSON.parse(serverResponse.data)
Introduction
A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:
SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected end of JSON input
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.
There are a few things you can try to fix this error:
-
Check that the content you are trying to parse is JSON format and not HTML or XML
-
Verify that there are no missing or extra commas.
-
Make sure to check for unescaped special characters.
-
Check for mismatched brackets or quotes.
-
Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
1. Check that the content you are trying to parse is JSON format and not HTML or XML
A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.
Consider the following front-end JavaScript code:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.
The fetch()
function then returns a promise, and when that promise resolves, we handle that with the response.json()
method. This just takes our JSON response and converts it to a JSON object to be used!
After that we just console.log out the data object
Now for the server-side of things, look on to our Node JS route that returns the JSON /data
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'text/html'); ❌ Not returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
We can see that it is setting the Header as text/html
. This will give you the error:
syntaxerror: unexpected token '<', "<!doctype "... is not valid json
This is because we are trying to parse the content with JSON.parse()
or in our case response.json()
and receiving a HTML file!
To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json')
:
...
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
res.end(JSON.stringify({ a: 1 }));
});
...
Whats
Content-Type
request header anyway?Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.
That is why still need to explicitly specify our request header
content-type
!
syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json
This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<
) and JSON is not valid with <
tags, it will through this error.
For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data)
you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json
.
Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data
route. If you misspelt this, you could be redirected to a 404 HTML page instead!
Tip: Use appropriate error handlers for non-JSON data
If you are using fetch()
to retrieve your data, we can add a catch handler to give meaningful error messages to the user:
fetch('https://localhost:3000/data')
.then(response => response.json())
.then(data => {
console.log(data);
// Use the data here
})
.catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */
If you are using JSON.parse()
we can do this in a try/catch block as follows:
try {
JSON.parse(data);
}
catch (error) {
console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}
JSON objects and arrays should have a comma between each item, except for the last one.
{
"name": "John Smith"
"age": 30
"address": {
"street": "123 Main St"
"city": "Anytown"
"state": "USA"
}
}
This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.
To fix this, you would add commas as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.
3. Make sure to use double quotes and escape special characters.
JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It's a lovely day"
}
When we try to parse this with JSON.parse
, we will get the error: SyntaxError: Invalid or unexpected token.
The problem is with the following line using a apostrophe:
"message": "It's a lovely day"
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
},
"message": "It's a lovely day"
}
As we can see, this will fix our error since we escape the aspostrophe as such:
"message": "It's a lovely day"
4. Check for mismatched brackets or quotes.
Make sure all brackets and quotes are properly closed and match up.
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.
To fix this, you would add the missing closing curly bracket as follows:
{
"name": "John Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "USA"
}
}
If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)
We can install jsonlint with npm as follows:
- Open up the terminal
- Run NPM install
npm install jsonlint -g
- We can then validate a file like so:
jsonlint myfile.json
Summary
In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch
or JSON.parse
. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.
In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.
To be really sure, check the JSON with tools like JSONLint to validate!
In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.
This guide will help you to fix SyntaxError: Unexpected token < in JSON at position 0
. This guide also applies to these other common variants of the same error:
-
SyntaxError: The string did not match the expected pattern.
-
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
-
JSON parse error: Unrecognised token '<'
Summary
These errors indicate that your JavaScript code expected to receive JSON but got something else instead (probably HTML in the form of a server-side error). To fix the issue, you need to examine what you got instead of the expected JSON to determine what the problem is.
Details
Usually, this error is caused when your server returns HTML (which typically begins with <DOCTYPE html>
or <html>
) instead of JSON. Valid JSON cannot begin with a <
character, so the JSON parser knows immediately that the data isn’t valid JSON and produces one of the error messages mentioned above.
To fix this error, you need to figure out why you’re getting HTML (or something else) instead of the JSON you expected. To do this, you need to log the data that you’re trying to parse to the console.
If you’re using fetch()
Use this approach if your code looks something like this:
fetch('https://example.com/some/path/to/json') .then(function (response) { return response.json(); }) .then(function (data) { // Do something with data });
In this case, the error is thrown when response.json()
tries to run and fails to parse the data from the server as JSON. You can add a function to handle the error, display the raw text of the response body from the server and log it to the console (see notes about commented lines below):
var responseClone; // 1 fetch('https://example.com/some/path/to/json') .then(function (response) { responseClone = response.clone(); // 2 return response.json(); }) .then(function (data) { // Do something with data }, function (rejectionReason) { // 3 console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4 responseClone.text() // 5 .then(function (bodyText) { console.log('Received the following instead of valid JSON:', bodyText); // 6 }); });
Here’s an explanation of each line with a numbered comment:
-
A
responseClone
variable is required to hold a clone of theresponse
object because the body of aresponse
can only be read once. Whenresponse.json()
is called, the body of the originalresponse
is read, which means it cannot be read again while handling the JSON parse error. Cloning theresponse
toresponseClone
provides two copies of the response body to work with; one in the originalresponse
to use withresponse.json()
and another to use withresponseClone.text()
ifresponse.json()
fails. -
This line populates the
responseClone
variable with a clone of the response received from the server. -
A second function argument is passed to the
then()
function that follows theresponse.json()
call. This second function will be called if the promise fromresponse.json()
is rejected (i.e. a JSON error is encountered). -
This line logs the
rejectionReason
from the rejectedresponse.json()
promise and theresponseClone
so it can be examined if needed (the HTTP status code is often useful for debugging, for example). -
Instead of trying to parse the response body from the server as JSON, it is processed as raw text.
-
The body text is logged to the console for examination.
If you’re using JSON.parse()
Use this method if the code that’s throwing the error looks like this:
JSON.parse(data);
In this case, you can log the data to the console if an error is encountered to see what it contains:
try { JSON.parse(data); } catch (error) { console.log('Error parsing JSON:', error, data); }
What do I do next?
Once you can see the data that’s causing the JSON parse error, it will hopefully provide a clue as to why you’re not getting the valid JSON you expect. Some of the most common issues that lead to this error are:
-
If you see HTML indicating a 404 Not Found error instead of the JSON you expect, check the URL you’re passing to
fetch()
and make sure that it’s correct. -
If you see HTML indicating a server error (such as a 500 error code), examine your server’s error logs to determine why your server is encountering an error instead of providing the JSON you expect.
-
If you cannot see anything or if you have an unusual jumble of characters, check your variable assignments and character encodings.
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 < in JSON at Position 0.»
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.
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.
{
"name": "animals",
"animals": [
"Dog",
"Cat",
"Mouse",
"Pig",
"Bear"
],
"hobbies": {
"football": false,
"reading": true
}
}
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.
// not valid JSON
{
x: 4
}
// valid JSON
{
"x": 4
}
Unexpected Token < in JSON at Position 0
From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the 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.
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.
- https://jsonformatter.org/
- https://jsonformatter.curiousconcept.com/
- https://codebeautify.org/jsonvalidator
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 < in JSON at position 0” is the error that I have seen most throughout my time of working as a software developer. Quite often it happens in a situation when 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.
fetch(‘url’).then(response => response.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.
fetch("url").then(async response => {
try {
const data = await response.json()
console.log('response data?', data)
} catch(error) {
console.log('Error happened here!')
console.error(error)
}
})
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:
fetch(‘url’, {
method: ‘GET’,
headers: {
‘Content-Type’: ‘application/json’
}
}).then(response => response.json())
As for the latter, I have seen the server sending an HTML file on a few occasions. Usually, a reason for this was an incorrect URL provided to the fetch
method, or the API server route was not set up correctly. For example, if you have a Single Page Application and a backend running Express.js server, it could be set up to always serve an index.html
file. Therefore, always double-check your URLs and API routes configuration.
Conclusion
JSON is an extremely popular format and is commonly used for data interchanging. We have talked about what JSON is, and what we can do when a parsing error is thrown. For starters, always double-check if the values you are dealing with are what you expect them to be, and remember, console.log() is your friend.