Back to NiceJSON
NiceJSON Blog/ How to Validate JSON: Syntax Checking vs Schema Validation

How to Validate JSON: Syntax Checking vs Schema Validation

Understand the difference between checking that JSON is well-formed and validating it against a JSON Schema, with practical examples and tools.

2 min read
  • json
  • validator
  • json-schema

Two kinds of "valid"

When people ask whether a JSON document is valid, they can mean two different things:

  1. Well-formed: the text follows JSON syntax and can be parsed.
  2. Schema-valid: the parsed data has the shape your application expects.

A document can be well-formed but still wrong for your app, for example {"age": "twenty"} when a number is required.

Step 1: syntax validation

Syntax validation answers one question: can a parser read this? It catches trailing commas, bad quotes, mismatched brackets, and invalid escapes.

Use an online validator such as NiceJSON: paste the text and any error is shown with its line and column. In code, a parse attempt is itself a validator:

function isValidJson(text) {
  try {
    JSON.parse(text);
    return true;
  } catch (error) {
    console.error("Invalid JSON:", error.message);
    return false;
  }
}

Step 2: schema validation

JSON Schema is a standard vocabulary for describing what valid data looks like.

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

This schema requires name and age, forces age to be a non-negative integer, and rejects unknown fields.

Validating with a library

import Ajv from "ajv";
 
const ajv = new Ajv();
const validate = ajv.compile(schema);
 
if (!validate(data)) {
  console.error(validate.errors);
}

Python has jsonschema, Java has networknt/json-schema-validator, and Go has gojsonschema.

Where to validate

  • At the boundary: validate every request body and third-party response before using it.
  • In CI: lint config files such as package.json and tsconfig.json on each commit.
  • In your editor: many editors flag syntax errors as you type.

Security note

Never trust parsed data just because it was syntactically valid. Validate types, ranges, and lengths before using values in queries, file paths, or HTML.

Quick checklist

  • Does it parse? Use a validator first.
  • Does it match the contract? Use a schema.
  • Are errors reported with enough context to debug? Log the path and message, not the whole payload if it contains sensitive data.