jsonvalidatorerrorstutorial

JSON Validator — How to Find and Fix JSON Errors

·9 min read·Tool Guides

What Does a JSON Validator Do?

A JSON validator checks your JSON text against the official JSON specification (RFC 8259) and reports whether it is syntactically valid. If a problem exists, it tells you the exact line and column — so you fix the real cause instead of scanning manually.

JSONKit's JSON Validator validates as you type — no button press needed. A green badge means valid and shows byte count and line count. A red badge shows the exact error location with a plain-English explanation.

Error Reference Table

Error MessageCauseFix
Unexpected token , at position NTrailing commaRemove last comma before } or ]
Unexpected token } at position NExtra closing braceCheck opening/closing bracket balance
Unexpected token ' at position NSingle quotesReplace all ' with "
Unexpected token u at position Nundefined valueReplace with null or remove the key
Expected property name or '}'Trailing comma in objectRemove comma before }
Unexpected end of JSON inputMissing closing bracketAdd missing } or ]
Bad escaped characterUnescaped backslashUse \\ for a literal backslash
Invalid numberNaN, Infinity, hexUse valid decimal number or null

The Most Common JSON Syntax Errors

Trailing comma — the most frequent mistake. JavaScript objects allow trailing commas; JSON does not.

json
// INVALID
{ "name": "Ravi", "age": 28, }

// VALID
{ "name": "Ravi", "age": 28 }

Single quotes — JSON requires double quotes for both keys and string values.

json
// INVALID
{ 'city': 'Surat' }

// VALID
{ "city": "Surat" }

Unquoted keys — valid in JavaScript object literals, invalid in JSON.

json
// INVALID
{ name: "Ravi" }

// VALID
{ "name": "Ravi" }

JavaScript-only valuesundefined, NaN, and Infinity have no JSON equivalent.

json
// INVALID
{ "count": undefined, "ratio": NaN, "limit": Infinity }

// VALID — use null or omit the key
{ "count": null, "ratio": null, "limit": null }

Comments — JSON has no comment syntax. Use JSONC or JSON5 if comments are needed.

How to Read the Error Location

JSONKit shows: Unexpected token at line 6, col 18

  • Line 6 — count down from line 1 in your JSON
  • Col 18 — count characters from the left of that line, starting at 1
  • The error is usually at or just before that position — look one token back (a missing comma is on the line above the reported position)

Tip: Use the JSON Formatter to indent your JSON first. Formatted JSON makes the line/column location easy to navigate.

Validate JSON in Code

JavaScript / Node.js:

javascript
function validateJSON(str) {
  try {
    return { ok: true, data: JSON.parse(str) };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

const result = validateJSON('{"name":"Ravi","age":28}');
if (!result.ok) console.error("Invalid JSON:", result.error);

Python:

python
import json

def validate_json(s: str):
    try:
        return json.loads(s)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
        return None

Go:

go
import (
    "encoding/json"
    "fmt"
)

func validateJSON(s string) error {
    var v interface{}
    if err := json.Unmarshal([]byte(s), &v); err != nil {
        return fmt.Errorf("invalid JSON: %w", err)
    }
    return nil
}

Bash / CLI with jq:

bash
# Validate a file — exits 0 if valid, non-zero if invalid
jq empty data.json && echo "Valid" || echo "Invalid"

# Validate inline
echo '{"name":"Ravi"}' | jq empty

Validate JSON in CI/CD

Add JSON validation to your build pipeline to catch malformed config or fixture files before deployment.

Pre-commit hook (Git):

bash
#!/bin/sh
# .git/hooks/pre-commit
for file in $(git diff --cached --name-only | grep '.json$'); do
  jq empty "$file" || { echo "Invalid JSON: $file"; exit 1; }
done

GitHub Actions step:

yaml
- name: Validate JSON files
  run: |
    find . -name "*.json" -not -path "*/node_modules/*" | while read f; do
      jq empty "$f" || exit 1
    done

Syntax Validation vs Schema Validation

Syntax validation answers: "Is this valid JSON?" Schema validation answers: "Does this JSON have the right shape for my API?"

AspectSyntax ValidationSchema Validation
ChecksRFC 8259 grammarField presence, types, ranges
CatchesCommas, quotes, bracketsMissing fields, wrong types
ToolJSON ValidatorJSON Schema Validator
SpeedInstantMilliseconds

For production APIs, use both: syntax validation at the HTTP layer, schema validation in your business logic.

Schema Validation with Ajv (Node.js)

javascript
import Ajv from "ajv";
import addFormats from "ajv-formats";

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

const schema = {
  type: "object",
  required: ["id", "name", "email"],
  properties: {
    id:    { type: "integer" },
    name:  { type: "string", minLength: 1 },
    email: { type: "string", format: "email" },
    age:   { type: "integer", minimum: 0, maximum: 150 },
  },
  additionalProperties: false,
};

const validate = ajv.compile(schema);
const valid = validate({ id: 1, name: "Ravi", email: "ravi@example.com" });
if (!valid) console.error(validate.errors);

Use JSONKit's JSON Schema Generator to auto-generate a starting schema from any JSON object, then tighten the constraints from there.

Try JSON Validator

Validate your JSON with full error details, instantly.