Common JSON Errors and How to Fix Them

Common JSON errors such as single quotes, leading zeros and comments

Quick answer: Most common JSON errors come from a handful of rules: strings and keys must use double quotes, there can be no trailing comma after the last item, comments are not allowed, every item needs a comma between it and the next, and only true, false and null are valid literals. Paste your JSON into a validator that shows the exact line and column, fix the first error, and validate again.

This guide explains the common JSON errors developers hit, what each error message means, and how to fix it, with examples in JavaScript and C#. You can test every example in our free JSON formatter and validator. It is part of our Programming and Development guide.

The JSON Rules in One Minute

JSON is defined by RFC 8259 and ECMA-404. The rules are strict and short:

  • Objects use { } with "key": value pairs; arrays use [ ].
  • Keys and strings must use double quotes.
  • Items are separated by commas, with no comma after the last item.
  • Values can be a string, number, object, array, true, false or null.
  • Numbers have no leading zeros, no plus sign, and no NaN or Infinity.
  • There is no comment syntax.
  • JSON exchanged between systems must be encoded as UTF-8.

Common JSON Errors and Their Fixes

1. Trailing Comma

{
  "name": "Kamran",
  "role": "Developer",
}

The comma after the last property is not allowed. Remove it. JavaScript object literals accept trailing commas, which is why this error is so common when copying code into JSON files.

2. Single Quotes Instead of Double Quotes

{'name': 'Kamran'}

JSON only accepts double quotes for keys and strings: {"name": "Kamran"}. This often happens when JSON is built by hand in Python or JavaScript code.

3. Unquoted Keys

{name: "Kamran", skills: ["C#", "SQL"]}

Every key must be a quoted string: {"name": "Kamran", "skills": ["C#", "SQL"]}.

4. Missing Comma Between Items

{
  "a": 1
  "b": 2
}

Add a comma after 1. Validators usually report the error at the start of the next item ("b"), so look at the line just before the reported position.

5. Comments in JSON

{
  // timeout in seconds
  "timeout": 30
}

Standard JSON has no comments, so parsers reject both // and /* */. Move notes to documentation, use a field such as "_comment", or use a format that supports comments (JSONC, JSON5 or YAML) only where your tools accept it.

6. Python or JavaScript Values

{"active": True, "manager": None, "score": NaN, "x": undefined}

JSON only knows lowercase true, false and null. Replace True, None, undefined and NaN. In Python, generate JSON with json.dumps() instead of printing a dictionary with str().

7. Unclosed Brackets or Quotes

{"items": [1, 2, 3}

Every { needs a }, every [ needs a ] and every string needs a closing ". A formatter with indentation makes the mismatch obvious.

8. Line Breaks and Bad Escapes Inside Strings

{"path": "C:\new\data", "note": "line one
line two"}

Backslashes must be escaped as \\, and real line breaks inside a string must be written as \n. Allowed escapes are \" \\ \/ \b \f \n \r \t and \uXXXX.

9. Invalid Numbers

{"code": 007, "price": .5, "change": +3}

Leading zeros, a missing digit before the decimal point and a plus sign are all invalid. Write 7, 0.5 and 3. If leading zeros matter, as in postal codes or phone numbers, store the value as a string: "007".

10. More Than One Top-Level Value

{"id": 1}
{"id": 2}

A JSON document holds exactly one value. Wrap multiple objects in an array: [{"id": 1}, {"id": 2}]. Logs written one object per line are JSON Lines (NDJSON), which must be parsed line by line.

What Common Error Messages Mean

Message you seeUsual cause
Unexpected token } in JSONTrailing comma before a closing brace
Unexpected token ‘ in JSONSingle quotes used instead of double quotes
Expected double-quoted property nameUnquoted key or trailing comma
Unexpected end of JSON inputMissing closing bracket, or an empty response
Unexpected token < in JSON at position 0The server returned HTML (often an error page), not JSON
Bad control character in string literalA real line break or tab inside a string

Exact wording differs between browsers and libraries, but the position number points to the character where parsing stopped. Our JSON validator converts that position into a line and column with a plain-English explanation.

Handling JSON Errors in Code

JavaScript

async function loadData(url) {
  const res = await fetch(url);
  const text = await res.text();
  try {
    return JSON.parse(text);
  } catch (err) {
    console.error("Invalid JSON from", url, err.message, text.slice(0, 200));
    throw err;
  }
}

Reading the body as text first lets you log what the server really sent. That is the fastest way to spot an HTML error page behind an “Unexpected token <” message.

C# and .NET (System.Text.Json)

using System.Text.Json;

try
{
    var order = JsonSerializer.Deserialize<Order>(json);
}
catch (JsonException ex)
{
    // LineNumber and BytePositionInLine are zero-based
    Console.WriteLine($"Invalid JSON at line {ex.LineNumber + 1}: {ex.Message}");
}

By default, System.Text.Json rejects comments and trailing commas. If you must read hand-edited config files, Microsoft’s System.Text.Json documentation shows how to allow them:

var options = new JsonSerializerOptions
{
    ReadCommentHandling = JsonCommentHandling.Skip,
    AllowTrailingCommas = true
};

Only relax these rules for files you control. APIs should keep sending and expecting strict JSON. If you are building APIs, our ASP.NET Core tutorial for beginners covers returning JSON from controllers.

How to Prevent JSON Errors

  • Never build JSON by joining strings; use JSON.stringify, JsonSerializer.Serialize or json.dumps.
  • Validate config files in your editor or CI pipeline before deploying.
  • Check the Content-Type and status code of API responses before parsing.
  • Keep large IDs as strings when sending them to JavaScript clients, to avoid precision loss.
  • Use a formatter with clear error positions when debugging, such as our online JSON formatter.

JSON is also the format behind structured data on websites. Our FAQ schema generator creates valid JSON-LD you can paste into a page. Data pipelines rely on clean JSON too, as covered in our guide to the best ETL tools.

Frequently Asked Questions

What is the most common JSON error?

Trailing commas and single quotes are the most frequent, especially when JSON is copied from JavaScript or Python code.

How do I find the error in a large JSON file?

Use a validator that reports the line and column, fix the first error it finds, then validate again. Later errors are often caused by the first one.

Can JSON have comments?

No. Standard JSON does not support comments. Some tools accept JSONC or JSON5, but APIs and most parsers do not.

Why do I get “Unexpected token < in JSON at position 0”?

The response starts with <, which usually means the server returned an HTML page, such as a login page or a 404 or 500 error, instead of JSON. Log the raw response to see it.

Is JSON case-sensitive?

Yes. Keys are case-sensitive, and the literals must be lowercase true, false and null.

Final Thoughts

Almost all common JSON errors come down to a few strict rules: double quotes, commas between items but not after the last one, no comments and only lowercase literals. Learn to read the error position, fix the first problem first, and let a good validator do the searching. Try it now with our free JSON formatter and validator, and find more developer guides in the Programming and Development guide.

Leave A Comment

Scroll to top