JSON

Why Is My JSON Invalid? Every Error Explained and Fixed (2026)

2026-05-25 · 9 min read · Validate JSON free →

You have JSON that should work but does not. The parser throws an error, your API call fails, your config file breaks the application on startup, or your code editor shows red underlines everywhere. JSON is unforgiving — one wrong character invalidates the entire document, and the error messages are often cryptic. This guide covers every cause of invalid JSON, with the exact fix for each one.

How to Find a JSON Error Instantly

Before anything else: paste your JSON into ToolPry's JSON Formatter. It validates in real time as you type and highlights the exact character and line where the error is. This single step solves most JSON problems in under 10 seconds. The formatter shows the error location in the source text, which is far more useful than the character position number most parsers report.

If you cannot share your JSON with an online tool (it contains sensitive production data), use the command line instead: python3 -m json.tool yourfile.json — it validates and prints the exact line and column of any error, with no data leaving your machine.

The 9 Most Common Reasons JSON Is Invalid

1. Trailing comma after the last item

This is the single most common JSON error. JavaScript allows trailing commas in objects and arrays. JSON does not. When you copy a JavaScript object literal into a JSON context, the trailing comma breaks parsing.

// INVALID
{
  "name": "Maria",
  "role": "admin",
}

// VALID
{
  "name": "Maria",
  "role": "admin"
}

The error message points to the closing brace, not the comma. Always check the line immediately before the closing bracket when the error points at } or ].

2. Single quotes instead of double quotes

JSON requires double quotes for all strings — both keys and values. Single quotes are valid JavaScript but invalid JSON. This trips up developers copying from JavaScript, Python dictionaries, or any language that uses single-quoted strings.

// INVALID
{'name': 'Maria', 'role': 'admin'}

// VALID
{"name": "Maria", "role": "admin"}

3. Unquoted keys

JavaScript object literals allow unquoted keys if they are valid identifiers. JSON requires all keys to be double-quoted strings — no exceptions.

// INVALID (valid JavaScript, invalid JSON)
{name: "Maria", role: "admin"}

// VALID
{"name": "Maria", "role": "admin"}

4. Comments

JSON does not support comments of any kind. Not //, not /* */, not #. If you need comments in configuration files, use JSONC (JSON with Comments, supported by VS Code), YAML, or TOML instead. Strip all comments before parsing standard JSON.

// INVALID
{
  // Server configuration
  "host": "localhost",
  "port": 5432
}

// VALID
{
  "host": "localhost",
  "port": 5432
}

5. Undefined, NaN, Infinity values

JSON has six types: string, number, boolean, null, object, array. JavaScript's undefined, NaN, and Infinity are not valid JSON values. If you serialise JavaScript objects that contain these, the result is invalid JSON.

// INVALID
{"score": NaN, "limit": Infinity, "data": undefined}

// VALID — convert to null or omit
{"score": null, "limit": null}

6. Unescaped special characters in strings

Inside a JSON string, double quotes and backslashes must be escaped with a backslash. Newlines must be written as \n, not actual line breaks. Windows file paths are particularly problematic because of their backslashes.

// INVALID
{"path": "C:\Users\Maria\Documents", "message": "She said "hello""}

// VALID
{"path": "C:/Users/Maria/Documents", "message": "She said \"hello\""}

The safest fix: use your language's JSON serialiser (JSON.stringify() in JavaScript, json.dumps() in Python) rather than constructing JSON strings by concatenation. The serialiser handles all escaping automatically.

7. Missing comma between properties

Every property in a JSON object must be separated by a comma. Every element in a JSON array must be separated by a comma. Forgetting a comma — especially when adding a new property to an existing object — is a common mistake.

// INVALID
{
  "name": "Maria"
  "role": "admin"
}

// VALID
{
  "name": "Maria",
  "role": "admin"
}

8. Mismatched brackets or braces

Every opening brace { needs a closing brace }. Every opening bracket [ needs a closing bracket ]. In deeply nested JSON, it is easy to lose track. The formatter's tree view helps immediately — it shows the nesting depth and makes mismatches obvious.

// INVALID — missing closing bracket
{
  "users": [
    {"name": "Maria"},
    {"name": "Carlos"}
}

// VALID
{
  "users": [
    {"name": "Maria"},
    {"name": "Carlos"}
  ]
}

9. Numbers formatted incorrectly

JSON numbers have specific rules. Leading zeros are not allowed (07 is invalid, use 7). Trailing decimal points are not allowed (1. is invalid, use 1.0 or 1). Numbers must not use commas as thousand separators (1,000 is invalid, use 1000). Scientific notation is supported (1.5e10 is valid).

// INVALID
{"price": 1,299.00, "count": 07, "ratio": 1.}

// VALID
{"price": 1299.00, "count": 7, "ratio": 1.0}

JSON Validation Across Different Tools and Languages

Browser console (Chrome/Firefox DevTools)

// Paste into console and press Enter
JSON.parse('{"name": "Maria", "role": "admin"}');
// Returns: {name: "Maria", role: "admin"} if valid
// Throws: SyntaxError: Unexpected token if invalid

Python command line

python3 -m json.tool data.json
# Outputs formatted JSON if valid
# Outputs "json.decoder.JSONDecodeError: ..." with line number if invalid

# Validate without formatting
python3 -c "import json; json.load(open('data.json'))"

Node.js

node -e "JSON.parse(require('fs').readFileSync('data.json','utf8')); console.log('Valid')"

Linux/Mac command line with jq

jq . data.json            # formats and validates
jq empty data.json        # validates only, no output if valid
echo $?                   # 0 = valid, 1 = invalid

Validating JSON in Code (Production Patterns)

Never let a JSON parse error crash your application without a useful error message. Wrap all JSON parsing in proper error handling and log the raw input when validation fails — this is the only way to debug JSON errors in production.

// JavaScript — safe parse with logging
function safeParse(text, context = 'unknown') {
  try {
    return { data: JSON.parse(text), error: null };
  } catch (err) {
    console.error(`JSON parse error in ${context}:`, err.message);
    console.error('Raw input (first 200 chars):', String(text).slice(0, 200));
    return { data: null, error: err.message };
  }
}

const { data, error } = safeParse(apiResponse, 'user endpoint');
if (error) {
  // handle gracefully
}

// Python — safe parse with logging
import json, logging

def safe_parse(text, context='unknown'):
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        logging.error(f"JSON parse error in {context}: {e}")
        logging.error(f"Input preview: {str(text)[:200]}")
        return None

JSON Schema Validation (Catching Structural Errors)

Syntax validation (is this valid JSON?) is just the first layer. Schema validation (does this JSON have the right structure and types?) catches a second class of problems: a required field is missing, a number field contains a string, an array is empty when it should have items.

// JavaScript — JSON Schema validation with Ajv
import Ajv from 'ajv'; // npm install ajv

const ajv = new Ajv();
const schema = {
  type: 'object',
  required: ['name', 'email', 'role'],
  properties: {
    name:  { type: 'string', minLength: 1 },
    email: { type: 'string', format: 'email' },
    role:  { type: 'string', enum: ['admin', 'editor', 'viewer'] },
    age:   { type: 'integer', minimum: 0 }
  },
  additionalProperties: false
};

const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
  console.log(validate.errors);
  // [{instancePath: '/email', message: 'must match format "email"'}]
}

Frequently Asked Questions

How do I validate JSON without sending it to an external tool?

Use your terminal: python3 -m json.tool yourfile.json validates and formats the file entirely locally. In VS Code, open a .json file — the editor validates it automatically and underlines errors. In Node.js: JSON.parse(fs.readFileSync('file.json', 'utf8')) throws a descriptive error if invalid.

Why does my JSON work in JavaScript but fail in other languages?

JavaScript is lenient about JSON. Some JavaScript engines accept trailing commas, single quotes, and comments in JSON-like data — features that are not part of the JSON specification. A strict JSON parser in Python, Java, or Go will reject these. The safest approach: validate with python3 -m json.tool or ToolPry's formatter before assuming your JSON is correct.

Can I fix invalid JSON automatically?

The json-repair npm package and similar tools attempt to fix common errors — trailing commas, single quotes, unquoted keys, truncated responses. These are useful for processing JSON from sources you do not control (scraped data, logs, user input). For JSON you generate yourself, fix the source rather than the output: use your language's JSON serialiser and never build JSON strings through string concatenation.

What is the difference between JSON and JSON5?

JSON5 is a non-standard extension that adds comments, trailing commas, single quotes, unquoted keys, multi-line strings, and hexadecimal numbers to JSON. It is used in some configuration files (.json5 extension). Standard JSON parsers reject JSON5 syntax. If your file uses JSON5 features, use a JSON5 parser library rather than the standard JSON.parse().

JSON Validation in CI/CD and Production Systems

JSON errors that slip into production cause real incidents. A malformed configuration file crashes a deployment. An invalid API response breaks a frontend feature. A corrupted database export fails silently. Adding JSON validation as an automated step — not just something developers do manually — prevents these failures from reaching production.

In a CI/CD pipeline, add a JSON validation step that runs before any deployment. The simplest version: a shell script that validates every JSON file in the repository. More sophisticated versions run schema validation against API responses in integration tests. The key is catching JSON errors when they are introduced — in a pull request — not when they are deployed.

## Simple CI validation step (GitHub Actions / any CI)
- name: Validate JSON files
  run: |
    find . -name "*.json" -not -path "*/node_modules/*" | while read file; do
      python3 -m json.tool "$file" > /dev/null && echo "✓ $file" || exit 1
    done

## More thorough: validate against JSON Schema
npm install -g ajv-cli
ajv validate -s schema.json -d data.json

In Node.js applications, use a JSON validation middleware at your API boundary that validates all incoming request bodies against a schema before they reach your handlers. This catches malformed JSON from clients before it causes cryptic errors deep in your code, and returns useful 400 error responses with specific validation messages.

Tools for Working with JSON at Scale

jq is the gold standard for JSON processing on the command line. It validates, formats, filters, transforms, and queries JSON. Install with brew install jq (Mac) or apt install jq (Ubuntu). For large JSON files where browser tools struggle, jq handles gigabyte-sized files efficiently through streaming.

VS Code validates JSON files automatically when the file has a .json extension or when the language mode is set to JSON. Errors appear as red underlines with explanations in the Problems panel. The built-in formatter (Shift+Alt+F) both validates and formats in one step.

Prettier enforces consistent JSON formatting across a project and fails builds when files are not formatted correctly. Add npx prettier --check "**/*.json" to your CI pipeline to prevent inconsistently formatted JSON from being merged.

For quick validation of any JSON without leaving your current task: ToolPry's JSON Formatter validates and highlights errors in real time as you type, shows the tree structure for navigating nested data, and works entirely client-side — no data leaves your browser.

Frequently Asked Questions

Why does my JSON work in Postman but fail in my code?

Postman is lenient with JSON — it sometimes accepts slight deviations from the spec. Your code's JSON parser (JavaScript's JSON.parse(), Python's json.loads()) is strict. The most common cause: Postman auto-repairs trailing commas or handles single quotes, masking errors that strict parsers reject. Validate your JSON with ToolPry's formatter or python3 -m json.tool to see the strict view of whether it is valid.

How do I validate nested JSON with deeply nested objects?

Deep nesting makes both reading and debugging JSON harder. The tree view in ToolPry's JSON Formatter lets you collapse and expand individual nodes, making it easy to navigate 10+ levels of nesting. For validation, mismatched brackets in deep nesting are best found by counting — a properly formatted JSON file has matching indentation levels, making mismatches visually apparent. The formatter's bracket-matching highlighting shows exactly which opening bracket corresponds to each closing bracket.

Can I validate JSON before saving it in my database?

Yes, and you should. In PostgreSQL, columns with type JSON or JSONB automatically validate that inserted data is valid JSON — invalid data is rejected with a parse error. In MySQL, JSON columns do the same. For application-level validation before the database call, parse the JSON in your code and catch the exception: if it throws, do not attempt the insert. Adding JSON Schema validation before storage also catches structural problems (wrong field types, missing required fields) before they compound into data quality issues.