When working with JSON (JavaScript Object Notation), sometimes you might encounter an error that mentions Unexpected token < in JSON at position 0
or Unexpected token o in JSON at position 1
. These are just examples – you might encounter a different token or a different position number. In this article, we’ll take a look at the different ways we can debug this particular error.
Why the Error Occurs
Generally, the error occurs because there is an invalid JSON syntax or an error is thrown from the server. Double check the JSON syntax to be certain that it is a valid JSON object. Example of valid JSON syntax:
{ "example1": [{ "id": 1, "first_name": "Ryun", "last_name": "Lathwood", "email": "rlathwood0@bandcamp.com", "gender": "Male", "ip_address": "211.73.218.126" }, { "id": 2, "first_name": "Goldarina", "last_name": "Peatman", "email": "gpeatman1@webs.com", "gender": "Female", "ip_address": "204.83.86.191" }], "example2": [{ "id": 3, "first_name": "Ken", "last_name": "Birch", "email": "kbirch1@arts.com", "gender": "Male", "ip_address": "211.56.78.190" }, { "id": 4, "first_name": "Jane", "last_name": "Carter", "email": "jcarter1@carter.com", "gender": "Female", "ip_address": "203.33.86.191" }] }
Characteristics of proper JSON syntax include:
- Double quotes surrounding property names and string value names (single quotes not allowed).
- If there are internal double quotes, be sure they are escaped
- Example:
{ "data": [{ "code: "1", "message": "This message has "unescaped" quotes. It will throw an error. This is the proper way to \"escape\" them." }] }
- Commas after each individual key:value pair (except the last key:value pair).
- Commas after each array (except for the last one).
Another possible reason for the error might be that the JSON being parsed isn’t actually JSON. Double check the response coming from the server to be sure that it’s returning a JSON response and not some sort of HTML or XML response (this is why we might get an uncaught syntaxerror: unexpected token < in JSON at position 0
error).
As you navigate this error, be sure to use the developer tools to your advantage. The console and the network tab will both be your friend as you debug these types of errors.
The more you work with JSON, the faster you will get at being able to interpret these types of errors!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.