Guides••11 min read

How to Validate JSON: Catch Errors Before Production

Validate JSON the right way. Understand syntax errors, read parser messages, set up schema validation, and integrate checks into CI. With practical examples.

By JSONEditor.net Team

Two levels of validation

"Validate this JSON" can mean two different things, and confusing them is a frequent source of bugs.

Syntax validation answers a yes/no question: is this string parseable JSON according to RFC 8259? That is what JSON.parse checks. If it throws, the bytes are not JSON. If it returns, they are.

Schema validation answers a structural question: does this valid JSON match the shape my program expects? An array of users where each item has a string email and a positive integer age. JSON.parse cannot answer that — you need a schema validator like Ajv or Zod.

Both matter. Syntax validation catches the file someone hand-edited with a trailing comma. Schema validation catches the API that started returning "age": "thirty" after a backend refactor. This post covers syntax first, then schema.

The seven syntax errors you will hit

After enough debugging sessions, the same handful of mistakes shows up over and over. Here they are with the actual byte that breaks the parser.

1. Trailing comma

{ "a": 1, "b": 2, }    // ← bad
{ "a": 1, "b": 2 }     // ← good

JavaScript object literals tolerate trailing commas. JSON does not. This is the single most common copy-paste failure when moving config from a .js file to a .json file.

2. Single quotes

{ 'name': 'Ada' }      // ← bad
{ "name": "Ada" }      // ← good

Only double quotes are valid string delimiters in JSON. Single quotes anywhere — keys or values — kill the parse.

3. Unquoted keys

{ name: "Ada" }        // ← bad (JavaScript object literal)
{ "name": "Ada" }      // ← good

4. Comments

{
  // version 2
  "host": "localhost"   // ← bad, JSON has no comments
}

If you need comments, you need JSON5 or JSONC, not JSON. Strip them before parsing or move them into a "_comment" key your code ignores.

5. Missing comma between pairs

{
  "a": 1
  "b": 2              // ← bad, missing comma after "1"
}

6. Unescaped characters in strings

{ "path": "C:\\Users\\ada" }   // ← good (backslashes escaped)
{ "path": "C:\Users\ada" }     // ← bad — \U is not a valid JSON escape
{ "path": "C:\Users
ada"     }                       // ← bad, literal newline in string

7. NaN, Infinity, undefined

{ "score": NaN }       // ← bad, not a JSON value
{ "score": null }      // ← good

Reading JavaScript error messages

Browsers and Node disagree slightly on wording but agree on the structure: error type, a description, and a position.

SyntaxError: Expected ',' or '}' after property value in JSON at position 23 (line 3 column 5)

Two pieces of information matter: position (the byte offset from the start of the string) and the expected token. The expected token tells you what the parser was looking for when it gave up. "Expected ','" almost always means a missing comma or a stray one. "Expected ':'" means a key without a value. "Unexpected token }" usually means a trailing comma.

In Node 20 and modern browsers the message includes the line and column. If you are still on older runtimes, here is the conversion you can drop into any error handler:

const lineCol = (text, position) => {
  let line = 1, col = 1;
  for (let i = 0; i < position && i < text.length; i++) {
    if (text[i] === '\n') { line++; col = 1; } else { col++; }
  }
  return { line, col };
};

try {
  JSON.parse(input);
} catch (err) {
  const pos = +/position (\d+)/.exec(err.message)?.[1];
  if (pos) console.error('At', lineCol(input, pos), '—', err.message);
  throw err;
}

Validating in the browser

The fastest manual path is the validator on this site — paste, click, get line and column. It runs entirely client-side so you can use it on production payloads without worrying about leaking data.

From devtools, a one-liner does the job:

try { JSON.parse(input); console.log('valid'); }
catch (e) { console.error(e.message); }

Validating in the terminal

jq exits non-zero on invalid JSON, which is all you need for scripts:

jq empty data.json && echo OK || echo BAD

The empty filter discards the output but forces a full parse. If you want a richer report, jq prints the error with its own position. Python is a fallback when jq is missing:

python3 -c "import json,sys; json.load(open(sys.argv[1]))" data.json

For directory-wide validation, combine with find:

find . -name '*.json' -exec sh -c 'jq empty "$1" 2>&1 || echo "FAIL: $1"' _ {} \;

Beyond syntax: JSON Schema

Syntactic JSON can still be wrong. {"age": "thirty"} parses fine but breaks the next thirty lines of your code. The standard solution is JSON Schema, a vocabulary for describing the expected shape of a document.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["email", "age"],
  "properties": {
    "email": { "type": "string", "format": "email" },
    "age":   { "type": "integer", "minimum": 0 }
  },
  "additionalProperties": false
}

Validate with Ajv in Node or the browser:

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true });
addFormats(ajv); // adds "email", "uri", "date-time", etc.

const validate = ajv.compile(schema);
if (!validate(data)) console.error(validate.errors);

Three practical tips for schemas. First, set additionalProperties: false on objects you control — it catches typos in keys. Second, use allErrors: true during development so you see every problem, not just the first one. Third, compile the validator once and reuse it; ajv.compile is slow but the compiled function is one of the fastest validators in any language.

If you already use TypeScript everywhere, Zod gives you runtime validation and a TypeScript type from a single declaration. It is heavier than Ajv at runtime but eliminates the duplication between the schema and the type.

Validating in CI

Catch broken JSON at the PR level, not in production. A two-line GitHub Actions step covers every .json file in the repo:

- name: Validate JSON files
  run: |
    set -euo pipefail
    find . -name '*.json' -not -path './node_modules/*' \
      -exec jq empty {} \;

For schema validation, do it at the application boundary. Validate API responses on the way in (a single bad payload should produce a clean error, not a downstream Cannot read property 'foo' of undefined) and validate request bodies on the way in to your server. Validation at the boundary means the rest of the codebase can trust its inputs.

Validation is not security

Two reminders that get forgotten in equal measure.

First, a string that parses as JSON can still contain attacks. {"name": "<script>alert(1)</script>"} is perfectly valid JSON. If you render it in HTML without escaping, you have an XSS. JSON validation tells you nothing about what is safe to render.

Second, untrusted JSON can exhaust memory. A 100-byte payload of {"a":{"a":{"a":... repeated produces a deeply nested object that crashes naive recursive code. If you accept JSON from the internet, cap the input size and the parse depth before you call JSON.parse. For browser code the limit is the tab's memory; for server code, set express.json({ limit: '100kb' }) or the equivalent.

For the day-to-day cases, the browser validator and a one-line CI check cover most of what goes wrong. Add schema validation when payload shape matters, which is most of the time.

JSONCSVConvertersData