JSON Validation Guide: How to Validate and Fix JSON Errors

β€’
DataFmt Team
β€’
#json #validation #debugging #web-development
5 min read

JSON Validation Guide: How to Validate and Fix JSON Errors

JSON (JavaScript Object Notation) is the most popular data format for APIs and configuration files. However, invalid JSON can break your applications. This guide will teach you how to validate and fix JSON errors effectively.

What is JSON Validation?

JSON validation ensures your data follows the correct JSON syntax rules. Valid JSON must:

  • Use double quotes for strings (not single quotes)
  • Have proper bracket matching {} and []
  • Separate items with commas
  • Not have trailing commas
  • Use valid data types (string, number, boolean, null, array, object)

Common JSON Errors

Error 1: Single Quotes Instead of Double Quotes

❌ Invalid:

{
  'name': 'John',
  'age': 30
}

βœ… Valid:

{
  "name": "John",
  "age": 30
}

Error 2: Trailing Commas

❌ Invalid:

{
  "name": "John",
  "age": 30,
}

βœ… Valid:

{
  "name": "John",
  "age": 30
}

Error 3: Unquoted Keys

❌ Invalid:

{
  name: "John",
  age: 30
}

βœ… Valid:

{
  "name": "John",
  "age": 30
}

Error 4: Comments in JSON

❌ Invalid:

{
  // This is a comment
  "name": "John",
  "age": 30
}

βœ… Valid:

{
  "name": "John",
  "age": 30
}

Note: Standard JSON doesn’t support comments. Use JSON5 or JSONC if you need comments.

Error 5: Missing Commas

❌ Invalid:

{
  "name": "John"
  "age": 30
}

βœ… Valid:

{
  "name": "John",
  "age": 30
}

How to Validate JSON

Method 1: Online JSON Validators

Use our Free JSON Validator to:

  • βœ… Paste your JSON and validate instantly
  • βœ… See exactly where errors occur
  • βœ… Get helpful error messages
  • βœ… Auto-format valid JSON
  • βœ… No installation required

Method 2: JavaScript Validation

function validateJSON(jsonString) {
  try {
    JSON.parse(jsonString);
    return { valid: true, error: null };
  } catch (error) {
    return { 
      valid: false, 
      error: error.message 
    };
  }
}

// Usage
const result = validateJSON('{"name": "John"}');
if (result.valid) {
  console.log('Valid JSON!');
} else {
  console.log('Error:', result.error);
}

Method 3: Command Line

Using Node.js:

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

Using jq (JSON processor):

jq . data.json

Using Python:

python -m json.tool data.json

JSON Schema Validation

For complex validation rules, use JSON Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "age": {
      "type": "number",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "email"]
}

Validate against schema in JavaScript:

import Ajv from 'ajv';

const ajv = new Ajv();
const schema = { /* your schema */ };
const validate = ajv.compile(schema);

const data = {
  "name": "John",
  "age": 30,
  "email": "[email protected]"
};

const valid = validate(data);
if (!valid) {
  console.log(validate.errors);
}

Best Practices for JSON Validation

1. Validate at the Boundaries

Always validate JSON when:

  • Receiving from external APIs
  • Reading from files
  • Accepting user input
  • Before saving to database

2. Provide Helpful Error Messages

function validateUserJSON(jsonString) {
  try {
    const data = JSON.parse(jsonString);
    
    if (!data.name) {
      throw new Error('Missing required field: name');
    }
    
    if (typeof data.age !== 'number') {
      throw new Error('Field "age" must be a number');
    }
    
    return { valid: true, data };
  } catch (error) {
    return { 
      valid: false, 
      error: error.message,
      line: extractLineNumber(error)
    };
  }
}

3. Use TypeScript for Type Safety

interface User {
  name: string;
  age: number;
  email: string;
}

function parseUser(jsonString: string): User {
  const data = JSON.parse(jsonString);
  
  // Runtime validation
  if (!isValidUser(data)) {
    throw new Error('Invalid user data');
  }
  
  return data as User;
}

function isValidUser(data: any): data is User {
  return (
    typeof data === 'object' &&
    typeof data.name === 'string' &&
    typeof data.age === 'number' &&
    typeof data.email === 'string'
  );
}

4. Handle Large JSON Files

For large files, use streaming parsers:

import { JSONParser } from '@streamparser/json';

const parser = new JSONParser();

parser.onValue = ({ value, key, parent, stack }) => {
  // Process value
  console.log(value);
};

// Stream data
stream.pipe(parser);

Common JSON Validation Tools

Browser DevTools

Chrome/Firefox DevTools automatically validate JSON:

  1. Open Network tab
  2. Click on API request
  3. View Response tab
  4. Invalid JSON will show error

VS Code Extensions

  • JSON Tools - Format and validate
  • JSON Schema Validator - Schema validation
  • Prettier - Auto-format JSON

Online Tools

  • DataFmt JSON Validator - Free, no signup
  • JSONLint - Popular online validator
  • JSON Formatter - Validate and beautify

Libraries

JavaScript:

  • ajv - JSON Schema validator
  • joi - Data validation
  • yup - Schema validation

Python:

  • jsonschema - JSON Schema validation
  • pydantic - Data validation

PHP:

  • json-schema - Validation library
  • Native json_decode() with error checking

Debugging JSON Errors

Finding the Error Line

function findJSONError(jsonString) {
  try {
    JSON.parse(jsonString);
    return null;
  } catch (error) {
    const match = error.message.match(/position (\d+)/);
    if (match) {
      const position = parseInt(match[1]);
      const lines = jsonString.substring(0, position).split('\n');
      return {
        line: lines.length,
        column: lines[lines.length - 1].length,
        message: error.message
      };
    }
    return { message: error.message };
  }
}

Visual Diff for JSON

Compare two JSON objects:

function compareJSON(json1, json2) {
  const obj1 = JSON.parse(json1);
  const obj2 = JSON.parse(json2);
  
  const diff = {};
  
  for (const key in obj1) {
    if (obj1[key] !== obj2[key]) {
      diff[key] = {
        old: obj1[key],
        new: obj2[key]
      };
    }
  }
  
  return diff;
}

API Response Validation

Fetch API with Validation

async function fetchJSON(url) {
  try {
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    const contentType = response.headers.get('content-type');
    if (!contentType?.includes('application/json')) {
      throw new Error('Response is not JSON');
    }
    
    const data = await response.json();
    return { success: true, data };
    
  } catch (error) {
    return { 
      success: false, 
      error: error.message 
    };
  }
}

Axios with Validation

import axios from 'axios';

axios.interceptors.response.use(
  response => {
    // Validate response data structure
    if (!isValidResponse(response.data)) {
      return Promise.reject(new Error('Invalid response format'));
    }
    return response;
  },
  error => {
    console.error('API Error:', error.message);
    return Promise.reject(error);
  }
);

Performance Tips

1. Cache Validation Results

const validationCache = new Map();

function validateWithCache(jsonString) {
  const hash = hashString(jsonString);
  
  if (validationCache.has(hash)) {
    return validationCache.get(hash);
  }
  
  const result = validateJSON(jsonString);
  validationCache.set(hash, result);
  return result;
}

2. Lazy Validation

Only validate when needed:

class LazyJSON {
  constructor(jsonString) {
    this._raw = jsonString;
    this._validated = false;
    this._data = null;
  }
  
  get data() {
    if (!this._validated) {
      this._data = JSON.parse(this._raw);
      this._validated = true;
    }
    return this._data;
  }
}

Security Considerations

1. Prevent JSON Injection

// ❌ DANGEROUS
const userInput = req.body.input;
const json = `{"data": "${userInput}"}`;
JSON.parse(json); // Vulnerable!

// βœ… SAFE
const data = {
  data: userInput
};
const json = JSON.stringify(data);

2. Validate Size Limits

function validateJSONSize(jsonString, maxBytes = 1000000) {
  const size = new Blob([jsonString]).size;
  
  if (size > maxBytes) {
    throw new Error(`JSON too large: ${size} bytes`);
  }
  
  return JSON.parse(jsonString);
}

3. Sanitize Before Display

function sanitizeJSON(obj) {
  return JSON.parse(JSON.stringify(obj, (key, value) => {
    if (typeof value === 'string') {
      return value.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
    return value;
  }));
}

Try Our JSON Validator

Ready to validate your JSON? Use our Free JSON Validator & Formatter:

  • πŸ” Instant validation with line numbers
  • ✨ Auto-formatting for valid JSON
  • 🎯 Clear error messages
  • πŸš€ No installation needed
  • πŸ”’ 100% client-side (private)
  • πŸ’― Free forever

Summary

Key Takeaways:

  1. Always validate JSON from external sources
  2. Use try-catch for JSON.parse()
  3. Provide clear error messages
  4. Consider JSON Schema for complex validation
  5. Validate at API boundaries
  6. Use proper tools and libraries
  7. Don’t forget security considerations

Common Mistakes to Avoid:

  • ❌ Trusting external JSON without validation
  • ❌ Ignoring parse errors
  • ❌ Using single quotes
  • ❌ Adding trailing commas
  • ❌ Forgetting to validate data types

Validate your JSON now! πŸš€


Need to validate JSON quickly? Try our free JSON validator tool!

Found this helpful? Try our free tools!

Explore Our Tools β†’