Error parsing json syntaxerror syntax error



SyntaxError: JSON.parse: bad parsing

Deeksha Agarwal

Posted On: April 5, 2018

26274 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

Источник

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.

Читайте также:  Fix apex legends engine error

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.

Источник

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 parsing json syntaxerror syntax 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.

Читайте также:  Как переводится с русского на английский error

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.

Источник

[Solved] SyntaxError: Unexpected end of JSON input

The Javascript error “SyntaxError: Unexpected end of JSON input” happens when you try to use JSON.parse() on an incomplete JSON string. Check your string for missing curly brackets ( > ) and / or unclosed double-quotes.

In yet another installment of “why won’t my JSON parse?”, we have the incomplete JSON string. This error comes up a lot when receiving incomplete responses from the server and may not be entirely your fault. But it’s still probably a little your fault.

Below is an example of some offending code:

If we try to run this through a Node interpreter, we’ll get the following error:

Yikes! That looks scary. But what’s the problem here? Well, if you know anything about JSON, you’ll immediately see what the issue is: your JSON string contains an incomplete JSON object. What should end up parsing into an object with one property, foo , with the value of “bar”, is missing its closing curly bracket.

Fix 1: close the curly bracket

If we close that JSON object with a matching left curly bracket, our code will look like this instead:

Much better! But this is a super simple example. If you’re getting this on your production code, and your code is talking to an API, it’s a good bet the server is just sending you an incomplete response. This could be due to network trouble or some error on the server causing it to abort the connection mid-response.

Fix 2: use JSON.stringify() to make JSON strings

If you’re hard-coding your own JSON strings, you’re gonna have a bad time. That’s a computer’s job! Of course, JSON is so easy to write and read, it’s very tempting to make something like this right there in your sever-side (if your server is Node) or client-side code:

And then run into trouble later because, even though it looks correct, it’s not valid JSON. That’s because valid JSON only has double quotes, not single quotes. So then you figure “alright, I’ll just make ’em double quotes then!”. And you do something silly like this:

Читайте также:  Error message with google chrome

And in your haste, you forgot the closing double-quote for the “bar” value, and now you have the same old “SyntaxError: Unexpected end of JSON input” you started with. Why is this so hard!? Because you’re trying to speak a totally different language than Javascript… inside a string… inside Javascript. That’s like, a lot of work. And very error prone.

Did you know Javascript has a built-in function so you don’t have to do this? Bet you didn’t. It’s called JSON.stringify() and apart from having a cool name, it can make your life a whole lot easier.

See that? Perfect JSON every time. That’s why making and reading JSON is best left up to computers. Yeah, it’s a popular serialization format because it’s human readable. But that doesn’t mean it’s supposed to be human write-able

(I know, lots of config files are now written in JSON. Leave me alone)

Fix 3: use jsonlint to check your JSON

Linters are super useful. They make sure your code isn’t dumb before you try to do stuff with it. jsonlint is a node package that can help you check your JSON before you wreck your JSON.

Install it like this:

Create a JSON file with the same contents as our broken string in the first example and save it as foo.json:

Then run jsonlint like this:

And you should have some output like the following:

Now that is a bit more helpful than “SyntaxError: Unexpected end of JSON input”, don’t you think? Our example is, again, trivial, but with a more complex JSON object to debug, you can see how jsonlint would be very useful.

Fix 4: catch the error

If you are expecting that you might get bad JSON and you just want to avoid your whole program crashing, you can also catch the error very simply:

Here, we wrap the JSON.parse() call in a try / catch block so that we can print an error message instead of having an unhandled exception float to the top of our call stack and make us look like a bunch of amateurs. Note that we are also making sure the exception is an instance of a SyntaxError so we don’t inadvertently catch something else and think it was the JSON syntax error. It’s just good practice to be specific in what exceptions you catch.

Conclusion

In this article we covered what causes “SyntaxError: Unexpected end of JSON input” and how to fix it, prevent it, or handle it. Which one of the fixes above you choose depends on your application. Sometimes, you might be getting JSON from the user, and you can’t assume it’ll be valid. So in that case it’s better to catch the error and deal with it. Otherwise, if you’re debugging something your API is returning to you, you may want to consider jsonlint or something similar.

Hope this helped. Till next time!

About the Author

Bill is a senior software engineer with 23 years of experience. He specializes in Python, Javascript, C/C++, DevOps, test driven development, and making sure your code isn’t terrible.

Источник

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