Сообщение
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:
JSON.parse('[1, 2, 3, 4,]');
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
Необходимо убрать последние запятые в строках и тогда ошибки не будет:
JSON.parse('[1, 2, 3, 4]');
JSON.parse('{"foo": 1}');
Названия свойств должны быть в двойных кавычках
Вы не можете использовать одинарные кавычки в именах свойств. Например, ‘foo’.
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
Вместо этого необходимо написать «foo»:
JSON.parse('{"foo": 1}');
Незначащие нули или плавающая точка без последующей цифры
Вы не можете использовать незначащие нули, например, 01. Плавающая точка должна всегда сопровождаться хотя бы одной цифрой после неё.
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
Вместо этого напишите просто 1 без нуля и используйте хотя бы одну цифру после точки:
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
Смотрите также
Содержание
- SyntaxError: JSON.parse: bad parsing
- Deeksha Agarwal
- JSON.Parse Syntax Errors
- Why the SyntaxError Horror?
- Exceptions¶
- Overview¶
- Base type¶
- Switch off exceptions¶
- Extended diagnostic messages¶
- Parse errors¶
- json.exception.parse_error.101¶
- json.exception.parse_error.102¶
- json.exception.parse_error.103¶
- json.exception.parse_error.104¶
- json.exception.parse_error.105¶
- json.exception.parse_error.106¶
- json.exception.parse_error.107¶
- json.exception.parse_error.108¶
- json.exception.parse_error.109¶
- json.exception.parse_error.110¶
- json.exception.parse_error.112¶
- How to Fix the ‘SyntaxError: JSON.parse: bad parsing ‘ Error in Our JavaScript App?
- Fix the ‘SyntaxError: JSON.parse: bad parsing’ When Developing JavaScript Apps
- Conclusion
- Related Posts
- By John Au-Yeung
- SyntaxError: JSON.parse: bad parsing
- Tired of getting this annoying error when your parsing your JSON? Read on to learn how!
- JSON.Parse Syntax Errors
- Why the SyntaxError Horror?
- How to Catch the Error Before Hand
SyntaxError: JSON.parse: bad parsing
Deeksha Agarwal
Posted On: April 5, 2018
26290 Views
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
Источник
Exceptions¶
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.
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
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.
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.
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.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.
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.
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.
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.
json.exception.parse_error.106¶
An array index in a JSON Pointer (RFC 6901) may be 0 or any number without a leading 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.
json.exception.parse_error.108¶
In a JSON Pointer, only
1 are valid escape sequences.
json.exception.parse_error.109¶
A JSON Pointer array index must be a number.
json.exception.parse_error.110¶
When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
json.exception.parse_error.112¶
An unexpected byte was read in a binary format or length information is invalid (BSON).
Источник
How to Fix the ‘SyntaxError: JSON.parse: bad parsing ‘ Error in Our JavaScript App?
By John Au-Yeung
Post date
Sometimes, we may run into the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps.
Fix the ‘SyntaxError: JSON.parse: bad parsing’ When Developing JavaScript Apps
To fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps, we should make sure we pass in a valid JSON string as an argument of the JSON.parse method.
Other possible error messages for various JSON parse errors include:
For instance, we shouldn’t pass in a JSON string that has trailing commas:
The first line has a trailing comma at the end of the array.
The 2nd has a trailing commas at the end of the object.
Instead, we should fix the error by removing them:
Also, property names must be double quoted strings, so instead of writing:
Also, we can’t have numbers with leading zeroes in our JSON string:
Instead, we fix that by removing the leading zero:
Trailing decimal points are also invalid JSON, so we can’t write:
Instead, we write:
Conclusion
To fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps, we should make sure we pass in a valid JSON string as an argument of the JSON.parse method.
To check if a string is JSON in JavaScript, we can use the JSON.parse method…
Sometimes, we may run into the “unexpected token o” error when parsing JSON in our…
Sometimes, we want to convert a JSON string into a JavaScript object. In this article,…
By John Au-Yeung
Web developer specializing in React, Vue, and front end development.
Источник
SyntaxError: JSON.parse: bad parsing
Tired of getting this annoying error when your parsing your JSON? Read on to learn how!
Join the DZone community and get the full member experience.
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 decides that today is not going to be your day.
JSON.Parse Syntax Errors
In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the JSON.parse() function, and this is the main function that throws errors. Nearly all JSON.parse errors are a subset of the SyntaxError error type. The debugging console throws around 32 different error 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
Similarly, in this example, I forgot to add the final > character.
How to Catch the Error Before Hand
The problem with debugging JSON errors is that you only get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be up to you to regression find the bugs. Usually, it’s not as difficult as it sounds.
The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com
If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.
Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse]:
If this doesn’t help, then you are in for one long debugging session.
Published at DZone with permission of Deeksha Agarwal . See the original article here.
Opinions expressed by DZone contributors are their own.
Источник
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.
Deeksha Agarwal
Posted On: April 5, 2018
26739 Views
3 Min Read
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
JSON.parse(‘[a,b, c, d, e, f,]’); |
Similarly, in this example I forgot to add }
JSON.parse(‘{«LambdaTest»: 1,’); |
How to Catch The Error Before Hand?
The problem with debugging JSON errors are that you get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be upto you to regression find the bugs. Usually it’s not as difficult as it sounds.
The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com
If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.
function validatingJSON (json) { var checkedjson try { checkedjson = JSON.parse(json) } catch (e) { } return checkedjson } |
Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse] 😛
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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 |
If this doesn’t help, then you are in for one long debugging session. Leave a comment below with your issue. I can help.
Deeksha Agarwal
Deeksha Agarwal is in Product Growth at LambdaTest and is also a passionate tech blogger and product evangelist.
Author’s Profile
Deeksha Agarwal
Deeksha Agarwal is in Product Growth at LambdaTest and is also a passionate tech blogger and product evangelist.
Got Questions? Drop them on LambdaTest Community. Visit now
Test your websites, web-apps or mobile apps seamlessly with LambdaTest.
- Selenium, Cypress, Playwright & Puppeteer Testing
- Real Devices Cloud
- Native App Testing
- Appium Testing
- Live Interactive Testing
- Smart Visual UI Testing
Book a Demo
JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.parse()
, as the Javascript standard specifies.
Using JSON.parse()
Javascript programs can read JSON objects from a variety of sources, but the most common sources are databases or REST APIs. A JSON object read from these sources enters a Javascript program in a “flat” string format that contains the object’s key-value pairs.
To create a valid string variable, you must surround the JSON string with single quotes.
let flatJSON = '{"a": "b", "c": 1, "d": {"e": 2}}';
JSON.parse()
requires one parameter: the flat JSON string to be converted into a JSON object. JSON.parse()
takes the flat JSON string directly or as a Javascript variable. Passing variables is easier and more readable than passing in a long flat JSON string.
JSON.parse('{"a", "b", "c", 1}');
let flatJSON2 = '{"a": "b", "c": 1, "d": {"e": 2}}';
JSON.parse(flatJSON2);
JSON.parse()
takes an optional second parameter which is called a “reviver.” A reviver is a function that converts the JSON data that JSON.parse()
cannot process by itself. This reviver function example handles undefined values:
let flatJSON3 = ‘{“a”: “b”, “c”: 1, “d”: {“e”: 2}}’;
let reviver = function(key, value) {
if(typeof value === 'undefined') { return null; }
;
let parsed = JSON.parse(flatJSON3, reviver);
Revivers convert empty values and complex objects into valid Javascript objects. The next section goes into the specifics of how this is done with common examples.
JSON.parse()
itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code.
If you force code into a JSON object with a string, you must use the Javascript eval()
function to convert it into something the Javascript interpreter understands. This process is prone to error and often causes problems with the converted code’s scope.
Revivers have the specific purpose of converting string data into valid Javascript types. You should make conversions within reviver functions as simple as possible. In rare cases, a specialized conversion might require a lot of calculations.
Handling JSON.parse() Special Cases with Revivers
Error Handling
Improperly-formatted data passed to JSON.parse()
raises an error, stops processing, and returns no processed data, even if the rest of the JSON is correct. If an error occurs, never assume that JSON.parse()
returns a specific value.
Depending on how you write your program, an error could stop the rest of your Javascript code from executing. Wrap calls to JSON.parse()
in a try catch statement so you can explicitly specify what happens if parsing fails.
try {
JSON.parse(input);
} catch (e) {
return undefined; // Or whatever action you want here
}
Array Data
JSON.parse()
converts array data into a Javascript array. The array data must be a valid JSON string.
This is an uncommon use for JSON.parse()
. It’s easier to declare an array in code instead of going through JSON first. Declare arrays inside your Javascript program whenever possible.
Dates
Dates are not a valid JSON type. Converting strings of a particular format into a Javascript date type is a common extra step after using JSON.parse()
. Several examples are shown below.
A reviver function that converts strings to dates may look like this, if using ISO standard date format:
function reviver(key, value) {
if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
return new Date(value);
}
}
The Javascript Date
object translates various string formats into dates. Always check whether the resulting date makes sense, even if the Date
object “understood” its format. Here’s an example of a string conversion that results in an invalid real-world date:
// Converted to valid date: 02/16/2021
let date1 = JSON.parse('{"test": "2021-02-16"}');
// Converted to invalid date: 02/30/2021
let date2 = JSON.parse('{"test": "2021-02-30"}');
Empty Values
Null values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. JSON.parse()
will fail if it encounters an undefined value.
Searching for undefined values in a JSON string is a possible workaround for this problem, but be careful not to match any instances of the word “undefined” in a string. A better solution is to search for and replace the undefined value with a similar empty value type:
let parsedVal = (typeof value === 'undefined') ? null : value;
Using JSON.parse() Safely
Wrap JSON.parse()
in a function to cover its limits, handing special cases appropriate to your needs. Include a reviver function in a closure to handle common data conversion needs.
When you need more specialized data conversion than your default reviver function can handle, add a second reviver function as a parameter to your safe parsing function. Call the second reviver function at the end of the default reviver function.
Putting all of this together with previous code examples, here’s a simple safe JSON parsing function:
function safeJsonParse(json, reviver) {
function defaultReviver(key, value) {
if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
return new Date(value);
}
if(typeof value === 'undefined') { return null; }
if(reviver !== undefined) { reviver(); }
}
try {
let json = JSON.parse(json, defaultReviver);
} catch(e) {
return null;
}
}
Conclusion
JSON.parse()
is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.
Enroll in our Intro to Programming Nanodegree Program today to learn more about JSON parsing with JSON.parse()
and other programming concepts.
Start Learning
Sometimes, we may run into the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps.
Fix the ‘SyntaxError: JSON.parse: bad parsing’ When Developing JavaScript Apps
To fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps, we should make sure we pass in a valid JSON string as an argument of the JSON.parse
method.
Other possible error messages for various JSON parse errors include:
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
SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge)
For instance, we shouldn’t pass in a JSON string that has trailing commas:
JSON.parse('[1, 2, 3, 4,]');
JSON.parse('{"foo": 1,}');
The first line has a trailing comma at the end of the array.
The 2nd has a trailing commas at the end of the object.
Instead, we should fix the error by removing them:
JSON.parse('[1, 2, 3, 4]');
JSON.parse('{"foo": 1}');
Also, property names must be double quoted strings, so instead of writing:
JSON.parse("{'foo': 1}");
We write:
JSON.parse('{"foo": 1}');
Also, we can’t have numbers with leading zeroes in our JSON string:
JSON.parse('{"foo": 01}');
Instead, we fix that by removing the leading zero:
JSON.parse('{"foo": 1}');
Trailing decimal points are also invalid JSON, so we can’t write:
JSON.parse('{"foo": 1.}');
Instead, we write:
JSON.parse('{"foo": 1.0}');
Conclusion
To fix the ‘SyntaxError: JSON.parse: bad parsing’ when we’re developing JavaScript apps, we should make sure we pass in a valid JSON string as an argument of the JSON.parse
method.
Web developer specializing in React, Vue, and front end development.
View Archive
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}