DevBolt
By The DevBolt Team··12 min read

How to Fix Invalid JSON: The 10 Most Common Errors and Solutions

JSONDebuggingHowTo

The "invalid JSON" error means your JSON text violates the strict syntax rules of the JSON specification. JSON requires double-quoted keys, double-quoted strings, no trailing commas, and no comments. The fix depends on which rule you broke. Below is a complete guide to finding and fixing every type of JSON parse error across every major language.

What Does "Invalid JSON" Mean?

When you pass a malformed string to a JSON parser, it throws an error. The exact message varies by language, but they all mean the same thing: the input is not valid JSON. Here is what the error looks like in the most common languages:

JavaScript
SyntaxError: Unexpected token ' in JSON at position 1
SyntaxError: Expected property name or '}' at position 45
SyntaxError: Unexpected end of JSON input
Python
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 3
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 5 column 1
json.decoder.JSONDecodeError: Extra data: line 1 column 20
Go
invalid character '\'' looking for beginning of value
invalid character '}' after object key:value pair
unexpected end of JSON input
Java
com.google.gson.JsonSyntaxException: Expected ':' at line 3 column 12
org.json.JSONException: Unterminated string at character 28

Every one of these errors points to the same root cause: the text you passed to the parser does not conform to RFC 8259, the JSON specification. The fastest way to find the problem is to paste your JSON into a JSON Formatter that highlights the exact error location.

The 10 Most Common JSON Errors (With Fixes)

1. Trailing Commas

The single most common JSON error. JavaScript and TypeScript allow trailing commas in objects and arrays, but JSON does not. Remove the comma after the last item.

Invalid JSON
{
  "name": "Alice",
  "roles": ["admin", "editor",],
  "age": 30,
}
Fixed
{
  "name": "Alice",
  "roles": ["admin", "editor"],
  "age": 30
}

2. Single Quotes Instead of Double Quotes

Python dictionaries and JavaScript objects both accept single quotes. JSON does not. Every string and every key must use double quotes.

Invalid JSON
{'name': 'Alice', 'active': true}
Fixed
{"name": "Alice", "active": true}

3. Unquoted Keys

JavaScript lets you write { name: "Alice" }. JSON requires { "name": "Alice" }. Every key must be a double-quoted string.

Invalid JSON
{name: "Alice", age: 30}
Fixed
{"name": "Alice", "age": 30}

4. Comments in JSON

JSON has no comment syntax. Neither // single-line comments nor /* */ block comments are allowed. If you need comments in configuration files, use JSONC (supported by VS Code and TypeScript's tsconfig.json) or switch to YAML.

Invalid JSON
{
  // API configuration
  "endpoint": "https://api.example.com",
  "timeout": 5000  /* milliseconds */
}
Fixed
{
  "endpoint": "https://api.example.com",
  "timeout": 5000
}

5. Missing Commas Between Items

A missing comma between key-value pairs or array elements causes the parser to see an unexpected token. This error is tricky because the parser reports the error on the line after the missing comma.

Invalid JSON
{
  "first": "Alice"
  "last": "Smith"
}
Fixed
{
  "first": "Alice",
  "last": "Smith"
}

6. Unclosed Brackets or Braces

Mismatched {} or [] brackets are especially common in deeply nested JSON. The error usually appears as "unexpected end of JSON input" because the parser reaches the end of the string while still expecting a closing bracket.

Invalid JSON — missing closing ]
{
  "users": [
    {"name": "Alice"},
    {"name": "Bob"}

}
Fixed
{
  "users": [
    {"name": "Alice"},
    {"name": "Bob"}
  ]
}

7. Invalid Escape Sequences (Windows Paths)

Backslashes in JSON start escape sequences. A bare \U or \d is not a valid escape. This most commonly appears with Windows file paths.

Invalid JSON
{"path": "C:\Users\docs\new_file.txt"}
Fixed — escape the backslashes
{"path": "C:\\Users\\docs\\new_file.txt"}

Alternatively, use forward slashes. Windows accepts them in most contexts: "C:/Users/docs/new_file.txt".

8. undefined, NaN, and Infinity Values

These are valid JavaScript values but not valid JSON. JSON.stringify() silently converts undefined to nothing and NaN/Infinity to null, but if you manually construct JSON strings with these values, the parser will reject them.

Invalid JSON
{
  "count": NaN,
  "max": Infinity,
  "callback": undefined
}
Fixed
{
  "count": null,
  "max": null
}

9. Duplicate Keys

The JSON spec technically allows duplicate keys, but the behavior is undefined. Most parsers silently use the last value, which leads to subtle bugs. Some strict validators flag this as an error.

Problematic JSON
{
  "name": "Alice",
  "name": "Bob"
}

Which name wins? It depends on the parser. Remove the duplicate to avoid unpredictable behavior. Use a JSON Schema Validator to catch duplicate keys automatically.

10. BOM (Byte Order Mark) at Start of File

Some editors (especially on Windows) save files with a UTF-8 BOM character (U+FEFF) at the beginning. The BOM is invisible in most editors but causes JSON.parse() to fail with "unexpected token" at position 0. The fix is to save the file as "UTF-8 without BOM" or strip the BOM in code.

Strip BOM in JavaScript
function stripBOM(text) {
  return text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
}

const data = JSON.parse(stripBOM(rawText));
Strip BOM in Python
import codecs

text = raw_text.lstrip(codecs.BOM_UTF8.decode("utf-8"))
data = json.loads(text)

How to Fix Invalid JSON: Step-by-Step

When you hit a JSON parse error, follow these five steps to find and fix the problem quickly.

  1. 1Paste into a JSON formatter. Copy your JSON and paste it into the DevBolt JSON Formatter. It will instantly highlight the error location and show the exact character causing the problem.
  2. 2Read the error position. Every JSON parser tells you where it failed. In JavaScript, at position 142 means character 142. In Python, line 5 column 3 gives you the exact coordinates. Go to that position in your text.
  3. 3Check the line BEFORE the error. The reported position is where the parser got confused, but the actual mistake is often one line earlier. A missing comma on line 4 shows up as an error on line 5 because the parser only realizes something is wrong when it encounters the next token.
  4. 4Strip non-JSON content. If the error is at position 0, your file likely has a BOM, a leading whitespace character, or non-JSON text before the opening { or [. Common culprits include HTML error pages returned by APIs, log prefixes, or the BOM character. Strip everything before the first bracket.
  5. 5Validate programmatically. Add JSON validation to your code so malformed input is caught early with a clear error message instead of crashing downstream. See the language-specific examples below.

Fixing JSON in Different Languages

Here is how to safely parse JSON and handle errors in the most common languages. Each example catches the parse error, extracts a useful error message, and avoids crashing your application.

JavaScript / Node.js

JavaScript
function safeParseJSON(text) {
  // Strip BOM if present
  if (text.charCodeAt(0) === 0xFEFF) {
    text = text.slice(1);
  }

  try {
    return { data: JSON.parse(text), error: null };
  } catch (err) {
    // Extract position from error message
    const match = err.message.match(/position\s+(\d+)/i);
    const position = match ? parseInt(match[1], 10) : null;

    return {
      data: null,
      error: err.message,
      position,
      // Show context around the error
      context: position !== null
        ? text.substring(Math.max(0, position - 20), position + 20)
        : null,
    };
  }
}

// Usage
const result = safeParseJSON(input);
if (result.error) {
  console.error("JSON parse error:", result.error);
  if (result.context) {
    console.error("Near:", result.context);
  }
}

Python

Python
import json

def safe_parse_json(text: str) -> tuple[dict | None, str | None]:
    """Parse JSON with detailed error reporting."""
    # Strip BOM
    if text.startswith("\ufeff"):
        text = text[1:]

    try:
        return json.loads(text), None
    except json.JSONDecodeError as e:
        error_msg = (
            f"Line {e.lineno}, Column {e.colno}: {e.msg}\n"
            f"Near: {text[max(0, e.pos - 20):e.pos + 20]}"
        )
        return None, error_msg

# Usage
data, error = safe_parse_json(raw_text)
if error:
    print(f"Invalid JSON: {error}")

Go

Go
package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

func safeParseJSON(text string) (map[string]any, error) {
    // Strip BOM
    text = strings.TrimPrefix(text, "\xef\xbb\xbf")

    var result map[string]any
    if err := json.Unmarshal([]byte(text), &result); err != nil {
        if syntaxErr, ok := err.(*json.SyntaxError); ok {
            start := max(0, int(syntaxErr.Offset)-20)
            end := min(len(text), int(syntaxErr.Offset)+20)
            return nil, fmt.Errorf(
                "JSON error at offset %d: %s\nNear: %s",
                syntaxErr.Offset, syntaxErr.Error(), text[start:end],
            )
        }
        return nil, err
    }
    return result, nil
}

CLI (jq, python)

The fastest way to validate JSON from the command line is jq or Python's built-in JSON module. Both give you clear error messages with line numbers.

Shell
# Validate with jq (returns error message and exit code 1 if invalid)
jq . data.json

# Validate with Python (no extra install required)
python3 -m json.tool data.json > /dev/null

# Validate from stdin
echo '{"key": "value",}' | jq .

# Validate and pretty-print
cat data.json | python3 -m json.tool --indent 2

Preventing JSON Errors

Catching errors after the fact is good. Preventing them in the first place is better. Here are four strategies that eliminate most JSON errors before they reach production.

  • Use a schema validator. Define the expected structure of your JSON with JSON Schema and validate incoming data against it. This catches structural errors (wrong types, missing fields) in addition to syntax errors. Try the DevBolt JSON Schema Validator to test your schemas.
  • Use TypeScript types + JSON serialization. Never build JSON strings by hand. Use JSON.stringify() in JavaScript or json.dumps() in Python to serialize objects. The serializer handles quoting, escaping, and formatting correctly every time.
  • Lint JSON files in CI. Add a JSON validation step to your CI pipeline. A simple find . -name '*.json' -exec jq . {} + in your GitHub Actions workflow catches broken JSON files before they are merged. Tools like jsonlint and prettier --check work as well.
  • Use JSONC for config files that need comments. If you need comments in JSON, use JSONC (JSON with Comments). VS Code, TypeScript (tsconfig.json), and ESLint all support JSONC natively. Use the .jsonc extension so editors and tools know to allow comments.

Deploying APIs that accept JSON payloads?

DigitalOcean App Platform deploys Node.js, Python, and Go apps from a Git repo with zero server config. Auto-scaling, free SSL, and built-in monitoring included. Ideal for running JSON-heavy API services.

Quick Reference: JSON Syntax Rules

Bookmark this table. If your JSON is broken, the cause is one of these:

RuleInvalidValid
Keys{name: "v"}{"name": "v"}
Strings'hello'"hello"
Trailing commas[1, 2,][1, 2]
Comments// noteNot supported
Special valuesNaN, undefinednull
Backslashes"C:\Users""C:\\Users"

Fix Your JSON Now

The fastest way to fix invalid JSON is to paste it into a tool that shows you exactly what is wrong. Use the DevBolt JSON Formatter & Validator to instantly identify and fix errors — it highlights the broken line, explains the problem, and formats your output with proper indentation. For complex nested structures, the JSON Visualizer renders your data as a collapsible tree so you can spot mismatched brackets at a glance. And if you need to query specific paths in large JSON files, the JSON Path Tester lets you run JSONPath expressions to extract exactly the data you need. All tools run entirely in your browser — no data leaves your machine.