How to Validate JSON: 5 Ways to Check for Errors

jsonvalidationdebuggingtoolsbest practices
Kavishka Gimhan
6 min read
How to Validate JSON: 5 Ways to Check for Errors

Advertisement

I spent three hours debugging an API integration last month. The error message was cryptic: "Invalid JSON." That's it. No line number, no explanation, just "Invalid JSON."

I checked my code. I checked the API endpoint. I checked the network requests. Everything looked fine. Finally, out of desperation, I pasted the JSON response into a validator. Two seconds later, I found it: a missing comma on line 47.

Three hours. For a missing comma.

That's when I learned the value of validating JSON before you start debugging. A quick validation check would have saved me hours of frustration. Now, I validate JSON religiously, and I want to show you how to do it too.

Here are five ways to validate JSON, from quick online checks to automated validation in your code.

Why Validate JSON?

Before we dive into the methods, let's talk about why validation matters. JSON is strict. One missing comma, one extra bracket, one unclosed quote, and your entire JSON file is invalid. The problem is, these errors aren't always obvious.

Here's a perfectly valid JSON:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

And here's the same JSON with a tiny error (missing comma):

{
  "name": "John"
  "age": 30,
  "city": "New York"
}

Can you spot the difference? It's subtle, but that missing comma after "John" breaks everything. A validator would catch this instantly and tell you exactly where the problem is.

Method 1: Online JSON Validators (The Fastest Way)

For quick validation, online tools are unbeatable. They're instant, require no setup, and give you clear error messages.

I use our JSON Formatter for this all the time. Here's how it works:

  1. Paste your JSON into the input box
  2. Click "Validate"
  3. If there's an error, you'll see exactly what's wrong and where

The validator will tell you things like:

  • "Expected ',' or '}' at line 5, column 12"
  • "Unterminated string at line 3"
  • "Unexpected token at line 8"

This is incredibly helpful. Instead of guessing where the error is, you get precise location information.

Best for: Quick checks, one-off validation, when you need immediate feedback

Pros:

  • Instant results
  • No installation required
  • Clear error messages with line numbers
  • Works on any device with a browser

Cons:

  • Requires internet connection
  • You're pasting data online (though our tool runs entirely in your browser)

Method 2: Browser Console (The Built-in Way)

Every modern browser has a built-in JSON validator: the JavaScript console. Here's how to use it:

  1. Open your browser's developer tools (F12 or right-click → Inspect)
  2. Go to the Console tab
  3. Type: JSON.parse('your json here')
  4. Press Enter

If the JSON is valid, you'll see the parsed object. If it's invalid, you'll get an error message.

Example with valid JSON:

JSON.parse('{"name": "John", "age": 30}')
// Returns: {name: "John", age: 30}

Example with invalid JSON:

JSON.parse('{"name": "John" "age": 30}')
// Error: Unexpected token " in JSON at position 18

The error message tells you exactly where the problem is (position 18 in this case).

Best for: Quick validation when you're already in the browser, testing API responses

Pros:

  • Already installed (it's your browser)
  • Works offline
  • Fast and simple

Cons:

  • Error messages can be cryptic
  • Requires manual typing or pasting
  • Not ideal for large files

Method 3: Code Editors and IDEs (The Developer's Way)

Most code editors have built-in JSON validation. Here's how it works in popular editors:

VS Code:

  • Just open a .json file
  • VS Code automatically validates it
  • Errors show up with red squiggly lines
  • Hover over the error to see details

Sublime Text:

  • Install the "JSONLint" package
  • It validates automatically as you type

Atom:

  • Install the "linter-jsonlint" package
  • Real-time validation with inline error messages

IntelliJ/WebStorm:

  • Built-in JSON validation
  • Errors highlighted automatically
  • Quick fixes for common issues

The advantage of editor validation is that it happens in real-time. You see errors as you type, which prevents problems before they happen.

Best for: When you're writing or editing JSON files, development work

Pros:

  • Real-time validation
  • Integrated into your workflow
  • Can fix errors automatically in some cases

Cons:

  • Requires a code editor
  • Setup needed for some editors
  • Not useful if you're not a developer

Method 4: Command Line Tools (The Automated Way)

If you're working with JSON files regularly, command-line tools are powerful. Here are some options:

Using Node.js:

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

If the JSON is valid, you'll get no output (which means success). If it's invalid, you'll see an error.

Using Python:

python -m json.tool file.json

This validates and pretty-prints the JSON. If there's an error, it tells you exactly what's wrong.

Using jq (a JSON processor):

jq . file.json

This validates and formats the JSON. If it's invalid, you'll get an error message.

Best for: Automation, scripts, batch processing multiple files

Pros:

  • Can be automated
  • Works in scripts and CI/CD pipelines
  • Fast for batch operations

Cons:

  • Requires command-line knowledge
  • Need to install tools
  • Not as user-friendly as GUI tools

Method 5: Programmatic Validation (The Integration Way)

If you're building an application, you'll want to validate JSON programmatically. Here's how in different languages:

JavaScript/Node.js:

function validateJSON(jsonString) {
  try {
    JSON.parse(jsonString);
    return { valid: true };
  } catch (error) {
    return { 
      valid: false, 
      error: error.message,
      position: error.message.match(/\d+/)?.[0] // Extract position if available
    };
  }
}

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

Python:

import json

def validate_json(json_string):
    try:
        json.loads(json_string)
        return {"valid": True}
    except json.JSONDecodeError as e:
        return {
            "valid": False,
            "error": str(e),
            "line": e.lineno,
            "column": e.colno
        }

# Usage
result = validate_json('{"name": "John"}')
if not result["valid"]:
    print(f"Invalid JSON: {result['error']} at line {result['line']}")

PHP:

function validateJSON($jsonString) {
    $decoded = json_decode($jsonString);
    $error = json_last_error();
    
    if ($error === JSON_ERROR_NONE) {
        return ['valid' => true];
    } else {
        return [
            'valid' => false,
            'error' => json_last_error_msg()
        ];
    }
}

Best for: Applications that receive JSON input, APIs, data processing pipelines

Pros:

  • Integrated into your application
  • Can provide custom error handling
  • Essential for production code

Cons:

  • Requires programming knowledge
  • Need to implement error handling
  • More complex than other methods

Common JSON Errors and How to Spot Them

After validating thousands of JSON files, I've seen the same errors over and over. Here are the most common ones:

1. Missing Commas

{
  "name": "John"
  "age": 30  // Missing comma after "John"
}

2. Trailing Commas

{
  "name": "John",
  "age": 30,  // Trailing comma (not allowed in JSON)
}

3. Unclosed Quotes

{
  "name": "John,  // Missing closing quote
  "age": 30
}

4. Unclosed Brackets

{
  "name": "John",
  "age": 30
  // Missing closing brace

5. Comments (Not Allowed)

{
  "name": "John",
  // This is a comment - not allowed in JSON
  "age": 30
}

6. Single Quotes Instead of Double

{
  'name': 'John',  // Should be double quotes
  'age': 30
}

A good validator will catch all of these and tell you exactly where they are.

Best Practices for JSON Validation

Here's what I've learned from validating JSON professionally:

  1. Validate Early: Check JSON as soon as you receive it, before processing. It's easier to catch errors early.

  2. Validate in Multiple Places: Validate on the client side (before sending), on the server side (when receiving), and in your database layer (before storing).

  3. Use Specific Error Messages: When validation fails, provide helpful error messages. "Invalid JSON" isn't helpful. "Missing comma at line 5, column 12" is.

  4. Log Validation Errors: Keep track of validation failures. They can reveal patterns and help you fix systemic issues.

  5. Validate Schema, Not Just Syntax: Syntax validation (is it valid JSON?) is different from schema validation (does it match the expected structure?). Consider both.

  6. Automate Validation: Don't rely on manual checks. Use automated validation in your development workflow, CI/CD pipeline, and production code.

Real-World Validation Scenarios

Here are some situations where validation saved me:

API Integration: A client's API was returning invalid JSON intermittently. We added validation on our end and could immediately identify when the problem was on their side, not ours.

Data Migration: During a database migration, we validated all JSON fields before importing. We caught hundreds of invalid entries that would have caused problems later.

User Input: A form was accepting JSON input from users. We validated it on the frontend (for immediate feedback) and backend (for security). This prevented malformed data from entering our system.

Configuration Files: We validate all JSON configuration files on application startup. If there's an error, the app fails fast with a clear error message instead of crashing mysteriously later.

The Bottom Line

Validating JSON is one of those things that seems optional until you spend three hours debugging a missing comma. Then it becomes essential.

For quick checks, use an online validator like our JSON Formatter. It's fast, free, and gives you clear error messages.

For development work, use your code editor's built-in validation. It catches errors as you type.

For automation and production code, validate programmatically. It's the only way to ensure data quality at scale.

The key is to validate early and often. Don't wait until something breaks. Validate JSON as soon as you receive it, and you'll save yourself hours of debugging.

Remember: JSON validation isn't about being paranoid. It's about catching errors before they become problems. A 30-second validation check can save you hours of debugging later.

Want to validate some JSON right now? Head over to our JSON Formatter, paste in your JSON, and click validate. You'll see immediately if there are any errors, and exactly where they are.

Trust me, your future self will thank you for validating now instead of debugging later.

Advertisement

K

About Kavishka Gimhan

Passionate writer and content creator sharing valuable insights and practical advice. Follow for more quality content and updates.

Related Articles

You might also be interested in these articles