fixing SyntaxError: Unexpected string/token in JSON at position

The v8 JSON parser, used in Node.js and in the Chrome browser's javascript implementations, is not forgiving, especially when compared to the more verbose Firefox parser. You may encounter errors like the following when the input JSON string is malformed:

SyntaxError: Unexpected string in JSON at position 1886

JSON is stricter than javascript, which causes mistakes:

  • Single quotes are not allowed.
  • Property names must be quoted.
  • Trailing commas are not allowed.

Assuming you have control over the JSON, here are approaches you can take to fixing this issue.

Use this syntax highlighter

If using Chrome, paste the offending JSON here to find the relevant offending line (data is kept locally in your browser).

Fix the JSON manually

The position in the error message indicates which byte within the file the error occurs around. Vim has a handy command to go to a particular byte offset: :goto. Open the problematic JSON file in vim and the following will bring you there:

:goto 1886

Look out for Unexpected token < in JSON at position 0

Unexpected token < in JSON at position 0 is likely one of the most common JSON parsing problems in the browser, particularly when consuming data from a server. In this case, check that your server is actually returning a 200 payload. In many cases, you may actually be hitting something like a 404 page, potentially an HTML document instead of JSON, rendering the response unparseable:

> JSON.parse("<html><head><title>404 Not Found</title></head></html>");
Uncaught SyntaxError: Unexpected token < in JSON at position 0

Use a linter or a smart editor

Using a linter like eslint-plugin-json in your build process can help catch syntax mistakes before you see them in running code. Microsoft's VSCode editor has pretty good JSON editing support built-in as well.

Don't write JSON yourself in the first place

Outside of simple configuration files, you should avoid serializing JSON yourself. Use Javascript's built-in JSON.stringify() function, or libraries in other languages, to create JSON strings from real objects.

If you want to generate "pretty" JSON, take note of the third parameter to JSON.stringify, which specifies the indentation level in spaces, a very useful tool for debugging JSON content:

> const obj = {a:1,b:[2,3]}

> JSON.stringify(obj);

> JSON.stringify(obj, null, 2);
  "a": 1,
  "b": [

Note that we leave the second parameter, a replacer function that can be used to blacklist keys from serialization, as null