- How to fix SyntaxError Unexpected Token in JSON
- 1. Check that the content you are trying to parse is JSON format and not HTML or XML
- Whats Content-Type request header anyway?
- syntaxerror: unexpected token ‘ 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 ‘ 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: If you are using JSON.parse() we can do this in a try/catch block as follows: JSON objects and arrays should have a comma between each item, except for the last one. 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: 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: 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: As we can see, this will fix our error since we escape the aspostrophe as such: 4. Check for mismatched brackets or quotes. Make sure all brackets and quotes are properly closed and match up. 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: 5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors. 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) Open up the terminal Run NPM install npm install jsonlint -g We can then validate a file like so: jsonlint myfile.json Summary 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. 👋 About the Author G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion. My aim to share what I have learnt with you! (and to help me remember 😅) 👉 See Also 👈 Источник How to handle invalid JSON parse error properly. 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 = ' '; 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 = ' '; 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 = ' '; 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 = ' '; 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 = ' '; 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: Источник SyntaxError: JSON.parse: bad parsing JSON.parse() обрабатывает (парсит) строку в формате JSON. Это строка должна соответствовать формату, иначе будет выведена ошибка, что был нарушен синтаксис. Examples JSON.parse() не допускает запятые Метод JSON.parse() не разрешает использование, так называемых, trailling запятых. Обе строки выдадут ошибку типа SyntaxError: JSON. parse ( '[1, 2, 3, 4,]' ) ; JSON . parse ( '' ) ; // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data Необходимо убрать последние запятые в строках и тогда ошибки не будет: JSON. parse ( '[1, 2, 3, 4]' ) ; JSON . parse ( '' ) ; Названия свойств должны быть в двойных кавычках Вы не можете использовать одинарные кавычки в именах свойств. Например, ‘foo’. JSON. parse ( "" ) ; // SyntaxError: JSON.parse: expected property name or '>' // at line 1 column 2 of the JSON data Вместо этого необходимо написать «foo»: Незначащие нули или плавающая точка без последующей цифры Вы не можете использовать незначащие нули, например, 01. Плавающая точка должна всегда сопровождаться хотя бы одной цифрой после неё. JSON. parse ( '' ) ; // SyntaxError: JSON.parse: expected ',' or '>' after property value // in object at line 1 column 2 of the JSON data JSON . parse ( '' ) ; // SyntaxError: JSON.parse: unterminated fractional number // at line 1 column 2 of the JSON data Вместо этого напишите просто 1 без нуля и используйте хотя бы одну цифру после точки: Смотрите также Found a content problem with this page? This page was last modified on 7 нояб. 2022 г. by MDN contributors. Your blueprint for a better internet. MDN Support Our communities Developers Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation. Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license. Источник
- Tip: Use appropriate error handlers for non-JSON data
- 3. Make sure to use double quotes and escape special characters.
- 4. Check for mismatched brackets or quotes.
- 5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
- Summary
- 👋 About the Author
- 👉 See Also 👈
- How to handle invalid JSON parse error properly.
- Why do we get JSON parse error?
- How to handle JSON parse error?
- 1. Using try-catch block
- 2. Using if-else block
- 3. Using try-catch block with JSON.parse()
- 4. Using try-catch block with JSON.parse() and JSON.stringify()
- SyntaxError: JSON.parse: bad parsing
- Examples
- JSON.parse() не допускает запятые
- Названия свойств должны быть в двойных кавычках
- Незначащие нули или плавающая точка без последующей цифры
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
How to fix SyntaxError Unexpected Token in JSON
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
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.
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:
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
We can see that it is setting the Header as text/html . This will give you the error:
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’) :
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 ‘
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 ‘
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:
If you are using JSON.parse() we can do this in a try/catch block as follows:
JSON objects and arrays should have a comma between each item, except for the last one.
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:
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:
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:
As we can see, this will fix our error since we escape the aspostrophe as such:
4. Check for mismatched brackets or quotes.
Make sure all brackets and quotes are properly closed and match up.
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:
5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.
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)
- Open up the terminal
- Run NPM install npm install jsonlint -g
- We can then validate a file like so: jsonlint myfile.json
Summary
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.
👋 About the Author
G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.
My aim to share what I have learnt with you! (and to help me remember 😅)
👉 See Also 👈
How to handle invalid JSON parse error properly.
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 = ' '; 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 = ' '; 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 = ' '; 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 = ' '; 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 = ' '; 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:
SyntaxError: JSON.parse: bad parsing
JSON.parse() обрабатывает (парсит) строку в формате JSON. Это строка должна соответствовать формату, иначе будет выведена ошибка, что был нарушен синтаксис.
Examples
JSON.parse() не допускает запятые
Метод JSON.parse() не разрешает использование, так называемых, trailling запятых.
Обе строки выдадут ошибку типа SyntaxError:
JSON.parse('[1, 2, 3, 4,]'); JSON.parse(''); // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data
Необходимо убрать последние запятые в строках и тогда ошибки не будет:
JSON.parse('[1, 2, 3, 4]'); JSON.parse('');
Названия свойств должны быть в двойных кавычках
Вы не можете использовать одинарные кавычки в именах свойств. Например, ‘foo’.
JSON.parse(""); // SyntaxError: JSON.parse: expected property name or '>' // at line 1 column 2 of the JSON data
Вместо этого необходимо написать «foo»:
Незначащие нули или плавающая точка без последующей цифры
Вы не можете использовать незначащие нули, например, 01. Плавающая точка должна всегда сопровождаться хотя бы одной цифрой после неё.
JSON.parse(''); // SyntaxError: JSON.parse: expected ',' or '>' after property value // in object at line 1 column 2 of the JSON data JSON.parse(''); // SyntaxError: JSON.parse: unterminated fractional number // at line 1 column 2 of the JSON data
Вместо этого напишите просто 1 без нуля и используйте хотя бы одну цифру после точки:
Смотрите также
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.