← All articles

How to Validate JSON: Syntax and Schema Validation

Validate JSON syntax with JSON.parse, Python's json.loads, jq, or in your browser — and learn how to check structure and types with JSON Schema.

Validating JSON means confirming that a string is both syntactically correct (it follows the JSON grammar) and, optionally, structurally correct (it matches the shape your application expects). This guide shows you how to validate JSON in JavaScript, Python, on the command line, and in your browser — and explains the crucial difference between syntax validation and schema validation.

Two Kinds of JSON Validation

Before validating anything, decide which question you're actually asking:

  • Syntax validation — "Is this valid JSON at all?" Checks quotes, commas, brackets, and value types against the JSON grammar. JSON.parse() does this.
  • Schema validation — "Does this JSON have the right fields, types, and constraints?" Checks that id is an integer, email is present, and so on. This needs JSON Schema and a validator like Ajv.

Most "validate JSON" searches mean syntax validation — so we'll start there.

How to Validate JSON in JavaScript

The simplest, most reliable syntax check is to attempt a parse and catch the error. JSON.parse() throws a SyntaxError on any invalid input:

function isValidJson(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}

isValidJson('{"name":"Ada"}');  // true
isValidJson("{'name':'Ada'}");  // false — single quotes
isValidJson('{"a":1,}');        // false — trailing comma

If you need the reason a string is invalid, capture the error message — it usually includes a position:

function validateJson(text) {
  try {
    return { valid: true, value: JSON.parse(text) };
  } catch (err) {
    return { valid: false, error: err.message };
  }
}

validateJson('{"a":1,}');
// { valid: false, error: "Expected double-quoted property name in JSON at position 7" }

Do not use a regular expression to validate JSON. JSON is a recursive grammar and cannot be correctly validated with regex — JSON.parse() is the canonical validator and is already built into every JavaScript runtime.

How to Validate JSON in Python

Python's json.loads() raises json.JSONDecodeError on invalid input, with the exact line and column:

import json

def is_valid_json(text):
    try:
        json.loads(text)
        return True
    except json.JSONDecodeError as e:
        print(f"Invalid JSON: {e.msg} at line {e.lineno} column {e.colno}")
        return False

is_valid_json('{"name": "Ada"}')   # True
is_valid_json('{"name": "Ada",}')  # False — trailing comma

How to Validate a JSON File on the Command Line

With jq

jq exits with a non-zero status if the input isn't valid JSON, which makes it ideal for scripts and CI:

# Prints nothing and exits 0 if valid; prints an error and exits non-zero if not
jq empty data.json && echo "valid" || echo "invalid"

With Python (no install)

python3 -m json.tool data.json > /dev/null && echo "valid"

In a CI pipeline

Validate every JSON file in a repo as a pre-commit or CI step so malformed config never reaches production:

# Fail the build if any .json file is invalid
find . -name '*.json' -not -path './node_modules/*' \
  -exec sh -c 'jq empty "$1" || exit 255' _ {} \;

Validate JSON in Your Browser

For a quick check without writing code, paste your JSON into fixjson's JSON validator. It reports the exact line and position of any syntax error as you type, and everything runs locally — nothing is sent to a server, so it's safe for sensitive payloads. If the JSON is broken and you want it repaired rather than just flagged, JSON Fix auto-corrects common errors.

Beyond Syntax: Validating Structure with JSON Schema

Syntactically valid JSON can still be wrong for your application — a missing required field, a string where you expected a number, an out-of-range value. To enforce structure, describe the expected shape with JSON Schema and validate against it with Ajv (JavaScript) or the jsonschema library (Python):

import Ajv from 'ajv';

const ajv = new Ajv();
const validate = ajv.compile({
  type: 'object',
  required: ['id', 'email'],
  properties: {
    id:    { type: 'integer' },
    email: { type: 'string' },
  },
});

validate({ id: 42, email: 'a@b.com' }); // true
validate({ id: '42' });                 // false — wrong type, missing email
// validate.errors holds the detailed reasons

Schema Validation on the Command Line

For CI checks of JSON against a schema, two CLIs cover most needs:

# Python — install once, then validate
pip install jsonschema
jsonschema --instance data.json schema.json && echo OK

# Node — Ajv as a CLI
npm i -g ajv-cli ajv-formats
ajv validate -c ajv-formats -s schema.json -d "data.*.json"

Validate JSON on Every Commit (Pre-Commit Hook)

To stop unvalidated JSON from being committed at all, wire a hook with husky + lint-staged:

// package.json
{
  "lint-staged": {
    "*.json": [
      "jq empty",                                  // syntax check
      "ajv validate -s schemas/$name.schema.json -d"
    ]
  }
}

# install the hook
npx husky add .husky/pre-commit "npx lint-staged"

For Python projects, the official pre-commit framework has a built-in check-json hook that runs json.loads on every staged file.

Common JSON Validation Errors

When validation fails, the cause is almost always one of these — each has a dedicated guide:

Frequently Asked Questions

How do I check if a string is valid JSON?

Pass it to JSON.parse() inside a try/catch (JavaScript) or json.loads() inside a try/except (Python). If it doesn't throw, it's valid. For a no-code check, use a browser validator.

Can I validate JSON with a regular expression?

No. JSON is a recursive grammar that regex cannot express correctly. Always use a real parser like JSON.parse().

What's the difference between validating and parsing JSON?

Parsing turns the text into a usable value; validating just confirms it could be parsed. In practice a successful parse is the validation — they're the same operation, you simply discard the result when you only care about validity.

How do I validate JSON against a schema?

Use JSON Schema with Ajv (JavaScript) or the jsonschema library (Python). Schema validation checks types, required fields, and constraints — not just syntax.

Validate JSON Now — No Setup

Paste your JSON into the JSON validator to see syntax errors instantly, with the exact line and position highlighted. Everything runs in your browser; no data leaves your machine.