Tutorials

How to Fix the Most Common JSON Errors

JSON looks a lot like a JavaScript object, which is exactly why people break it. JSON is stricter than JavaScript, and a parser will reject the whole document over one stray character. This guide covers the mistakes behind most “Unexpected token” errors and how to fix each one.

The rules JSON actually enforces

  • Text strings and property names must use double quotes. Single quotes are not valid.
  • Property names must always be quoted.
  • No trailing comma after the last item in an object or array.
  • No comments of any kind.
  • Allowed values are strings, numbers, true, false, null, objects and arrays. undefined and NaN are not valid.

A broken example and its fix

This looks reasonable but fails in three places: single quotes, an unquoted key and a trailing comma.

{'name': 'Ana', age: 30,}

The valid version is:

{"name": "Ana", "age": 30}

A calm way to debug

  1. Paste the text into the JSON Formatter and Validator and choose Validate.
  2. Read the error message. Most browsers include a position or the unexpected character.
  3. Fix that one problem, then validate again. Later errors are often hidden behind the first one.
  4. When it is valid, use Format to indent it for reading, or Minify to make it compact.

Things a formatter will not fix

A valid file can still be wrong for your purpose, such as a misspelled key. Also, JavaScript stores numbers as 64-bit floating point values, so integers beyond about 9 quadrillion can lose precision when a browser tool parses and reprints them. If you work with very large identifiers, keep them as strings. Finally, if an object repeats a key, most parsers silently keep the last one, so a successful validation does not prove the data is what you intended.