JSON

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

2026-05-11 · 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 whole document, and the error messages are often cryptic. This guide goes through each cause of invalid JSON, with the exact fix for each one.

Almost every "invalid JSON" case is one of six things JSON forbids but JavaScript allows: trailing commas, single-quoted strings, unquoted keys, comments, the values undefined/NaN/Infinity, and a stray byte-order mark at the start. JSON is not a subset of JavaScript you can eyeball. Its grammar is fixed by RFC 8259 / ECMA-404. ToolPry's JSON Formatter validates against exactly those rules in your browser (nothing is uploaded) and highlights the first violation, usually a character before the offset the native parser reports.

What "invalid JSON" means

Invalid JSON is text that breaks the JSON grammar in RFC 8259, so a parser refuses to read it. The parser stops at the first character that cannot appear at that point and reports it; Chrome and Node.js, for example, print messages such as Unexpected token or Expected property name with the offending character or position. Valid JSON follows a short list of rules:

  • Keys and strings use double quotes: "name", never 'name' or a bare name.
  • Values are only objects, arrays, strings, numbers, true, false or null. undefined, NaN, Infinity, dates and functions are not JSON values.
  • No comma after the last item, and no comments.
  • Inside a string, the quotation mark, the backslash and the control characters U+0000 to U+001F (such as a raw tab or line break) must be escaped, for example \", \\, \n. An unescaped one is what "invalid characters in JSON" errors usually mean.

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 one step solves most JSON problems in under 10 seconds. The formatter shows the error location in the source text, which is more useful than the character position 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 the file 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 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"
}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

The error message points to the closing brace, not the comma. When it points at } or ], check the line just before it.

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"}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

3. Unquoted keys

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

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

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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
}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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 literal line breaks. Windows file paths often break here because of their backslashes.

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

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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

Properties in a JSON object and elements in a JSON array must be separated by commas. Forgetting a comma is a common mistake, especially when you add a new property to an existing object.

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

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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 here: it shows the nesting depth and makes mismatches obvious.

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

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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'))"

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

Node.js

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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 error handling and log the raw input when validation fails. That logged input 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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

JSON Schema Validation (Catching Structural Errors)

Syntax validation (is this valid JSON?) is only 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"'}]
}

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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. Making JSON validation an automated step, rather than something developers do by hand, keeps these failures out of 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 goal is to catch JSON errors when they are introduced, in a pull request, rather than 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

Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.

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 standard tool 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) 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, so no data leaves your browser.

Invalid JSON FAQ

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?

Usually because the data was never parsed as JSON in JavaScript. JSON.parse() is strict in every JavaScript engine, but JavaScript object literals, and config loaders that evaluate JavaScript or accept JSON5, allow trailing commas, single quotes and comments. Those are not part of the JSON specification, so a JSON parser in Python, Java or Go rejects them. 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().

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.

Summary: Fixing Invalid JSON

When JSON "should work but doesn't," stop re-reading it and let a strict parser find the spot: paste it into the ToolPry JSON Formatter, fix the first highlighted error, then re-validate. Clearing the first error often removes several phantom ones downstream. For config files, add a validation step in CI so a bad comma fails the build, not production.