Json javascript parse error



SyntaxError: JSON.parse: bad parsing

Deeksha Agarwal

Posted On: April 5, 2018

26259 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

Источник

Json javascript parse error

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

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

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

If you’re trying to parse a JSON string to a native JavaScript value, you have to make sure the value is valid JSON before parsing it, or you can use a try/catch block to handle any errors.

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

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

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

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

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

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

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

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

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

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

Make sure your server sends a valid JSON response #

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

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

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

Источник

SyntaxError: JSON.parse: bad parsing

Deeksha Agarwal

Posted On: April 5, 2018

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

Читайте также:  Fresh sans and error sans

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

Источник

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.

Related Posts

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.

Источник

Error handling, «try. catch»

No matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.

Usually, a script “dies” (immediately stops) in case of an error, printing it to console.

But there’s a syntax construct try. catch that allows us to “catch” errors so the script can, instead of dying, do something more reasonable.

The “try…catch” syntax

The try. catch construct has two main blocks: try , and then catch :

It works like this:

  1. First, the code in try <. >is executed.
  2. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch .
  3. If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) . The err variable (we can use any name for it) will contain an error object with details about what happened.

So, an error inside the try <. >block does not kill the script – we have a chance to handle it in catch .

Let’s look at some examples.

An errorless example: shows alert (1) and (2) :

An example with an error: shows (1) and (3) :

For try. catch to work, the code must be runnable. In other words, it should be valid JavaScript.

It won’t work if the code is syntactically wrong, for instance it has unmatched curly braces:

The JavaScript engine first reads the code, and then runs it. The errors that occur on the reading phase are called “parse-time” errors and are unrecoverable (from inside that code). That’s because the engine can’t understand the code.

So, try. catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”.

If an exception happens in “scheduled” code, like in setTimeout , then try. catch won’t catch it:

That’s because the function itself is executed later, when the engine has already left the try. catch construct.

To catch an exception inside a scheduled function, try. catch must be inside that function:

Error object

When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to catch :

For all built-in errors, the error object has two main properties:

name Error name. For instance, for an undefined variable that’s «ReferenceError» . message Textual message about error details.

There are other non-standard properties available in most environments. One of most widely used and supported is:

stack Current call stack: a string with information about the sequence of nested calls that led to the error. Used for debugging purposes.

Optional “catch” binding

If we don’t need error details, catch may omit it:

Using “try…catch”

Let’s explore a real-life use case of try. catch .

As we already know, JavaScript supports the JSON.parse(str) method to read JSON-encoded values.

Usually it’s used to decode data received over the network, from the server or another source.

We receive it and call JSON.parse like this:

You can find more detailed information about JSON in the JSON methods, toJSON chapter.

If json is malformed, JSON.parse generates an error, so the script “dies”.

Should we be satisfied with that? Of course not!

This way, if something’s wrong with the data, the visitor will never know that (unless they open the developer console). And people really don’t like when something “just dies” without any error message.

Let’s use try. catch to handle the error:

Here we use the catch block only to show the message, but we can do much more: send a new network request, suggest an alternative to the visitor, send information about the error to a logging facility, … . All much better than just dying.

Throwing our own errors

What if json is syntactically correct, but doesn’t have a required name property?

Here JSON.parse runs normally, but the absence of name is actually an error for us.

To unify error handling, we’ll use the throw operator.

“Throw” operator

The throw operator generates an error.

Technically, we can use anything as an error object. That may be even a primitive, like a number or a string, but it’s better to use objects, preferably with name and message properties (to stay somewhat compatible with built-in errors).

JavaScript has many built-in constructors for standard errors: Error , SyntaxError , ReferenceError , TypeError and others. We can use them to create error objects as well.

Their syntax is:

For built-in errors (not for any objects, just for errors), the name property is exactly the name of the constructor. And message is taken from the argument.

Let’s see what kind of error JSON.parse generates:

As we can see, that’s a SyntaxError .

And in our case, the absence of name is an error, as users must have a name .

So let’s throw it:

In the line (*) , the throw operator generates a SyntaxError with the given message , the same way as JavaScript would generate it itself. The execution of try immediately stops and the control flow jumps into catch .

Now catch became a single place for all error handling: both for JSON.parse and other cases.

Rethrowing

In the example above we use try. catch to handle incorrect data. But is it possible that another unexpected error occurs within the try <. >block? Like a programming error (variable is not defined) or something else, not just this “incorrect data” thing.

Of course, everything’s possible! Programmers do make mistakes. Even in open-source utilities used by millions for decades – suddenly a bug may be discovered that leads to terrible hacks.

In our case, try. catch is placed to catch “incorrect data” errors. But by its nature, catch gets all errors from try . Here it gets an unexpected error, but still shows the same «JSON Error» message. That’s wrong and also makes the code more difficult to debug.

To avoid such problems, we can employ the “rethrowing” technique. The rule is simple:

Catch should only process errors that it knows and “rethrow” all others.

The “rethrowing” technique can be explained in more detail as:

  1. Catch gets all errors.
  2. In the catch (err) <. >block we analyze the error object err .
  3. If we don’t know how to handle it, we do throw err .

Usually, we can check the error type using the instanceof operator:

We can also get the error class name from err.name property. All native errors have it. Another option is to read err.constructor.name .

In the code below, we use rethrowing so that catch only handles SyntaxError :

The error throwing on line (*) from inside catch block “falls out” of try. catch and can be either caught by an outer try. catch construct (if it exists), or it kills the script.

So the catch block actually handles only errors that it knows how to deal with and “skips” all others.

The example below demonstrates how such errors can be caught by one more level of try. catch :

Here readData only knows how to handle SyntaxError , while the outer try. catch knows how to handle everything.

try…catch…finally

Wait, that’s not all.

The try. catch construct may have one more code clause: finally .

If it exists, it runs in all cases:

  • after try , if there were no errors,
  • after catch , if there were errors.

The extended syntax looks like this:

Try running this code:

The code has two ways of execution:

  1. If you answer “Yes” to “Make an error?”, then try -> catch -> finally .
  2. If you say “No”, then try -> finally .

The finally clause is often used when we start doing something and want to finalize it in any case of outcome.

For instance, we want to measure the time that a Fibonacci numbers function fib(n) takes. Naturally, we can start measuring before it runs and finish afterwards. But what if there’s an error during the function call? In particular, the implementation of fib(n) in the code below returns an error for negative or non-integer numbers.

The finally clause is a great place to finish the measurements no matter what.

Here finally guarantees that the time will be measured correctly in both situations – in case of a successful execution of fib and in case of an error in it:

You can check by running the code with entering 35 into prompt – it executes normally, finally after try . And then enter -1 – there will be an immediate error, and the execution will take 0ms . Both measurements are done correctly.

In other words, the function may finish with return or throw , that doesn’t matter. The finally clause executes in both cases.

Please note that result and diff variables in the code above are declared before try. catch .

Otherwise, if we declared let in try block, it would only be visible inside of it.

The finally clause works for any exit from try. catch . That includes an explicit return .

In the example below, there’s a return in try . In this case, finally is executed just before the control returns to the outer code.

The try. finally construct, without catch clause, is also useful. We apply it when we don’t want to handle errors here (let them fall through), but want to be sure that processes that we started are finalized.

In the code above, an error inside try always falls out, because there’s no catch . But finally works before the execution flow leaves the function.

Global catch

The information from this section is not a part of the core JavaScript.

Let’s imagine we’ve got a fatal error outside of try. catch , and the script died. Like a programming error or some other terrible thing.

Is there a way to react on such occurrences? We may want to log the error, show something to the user (normally they don’t see error messages), etc.

There is none in the specification, but environments usually provide it, because it’s really useful. For instance, Node.js has process.on(«uncaughtException») for that. And in the browser we can assign a function to the special window.onerror property, that will run in case of an uncaught error.

The role of the global handler window.onerror is usually not to recover the script execution – that’s probably impossible in case of programming errors, but to send the error message to developers.

There are also web-services that provide error-logging for such cases, like https://errorception.com or https://www.muscula.com.

They work like this:

  1. We register at the service and get a piece of JS (or a script URL) from them to insert on pages.
  2. That JS script sets a custom window.onerror function.
  3. When an error occurs, it sends a network request about it to the service.
  4. We can log in to the service web interface and see errors.

Summary

The try. catch construct allows to handle runtime errors. It literally allows to “try” running the code and “catch” errors that may occur in it.

There may be no catch section or no finally , so shorter constructs try. catch and try. finally are also valid.

Error objects have following properties:

  • message – the human-readable error message.
  • name – the string with error name (error constructor name).
  • stack (non-standard, but well-supported) – the stack at the moment of error creation.

If an error object is not needed, we can omit it by using catch < instead of catch (err) < .

We can also generate our own errors using the throw operator. Technically, the argument of throw can be anything, but usually it’s an error object inheriting from the built-in Error class. More on extending errors in the next chapter.

Rethrowing is a very important pattern of error handling: a catch block usually expects and knows how to handle the particular error type, so it should rethrow errors it doesn’t know.

Источник

Оцените статью
toolgir.ru
Adblock
detector