Toolypet
Back to Blog
Dev

JSON Formatter & Validator Practical Guide - From Debugging to Validation

Can't read your API response? Master JSON formatting, validation, and common syntax error fixes with practical examples.

Toolypet Team

Toolypet Team

Development Team

5 min read

JSON Formatter & Validator Practical Guide

"I can't figure out where anything is in this API response..."

Have you ever received a JSON response compressed into a single line? Finding a specific field in a 3,000-character nested object is a nightmare.

JSON Formatter solves this problem. And Validator answers the question "Why won't this parse?"


JSON 30-Second Review

Data Types

{
  "string": "text",
  "number": 42,
  "boolean": true,
  "null": null,
  "array": [1, 2, 3],
  "object": {"nested": "value"}
}

Core Rules (Common Mistakes)

RuleCorrectWrong
Key quotes{"name": "value"}{name: "value"}
Strings"double quotes"'single quotes'
Trailing comma"a": 1}"a": 1,}
CommentsNot allowed// comment

Minified vs Prettified

Actual API Response (Minified)

{"users":[{"id":1,"name":"John Dev","email":"john@dev.com","profile":{"avatar":"https://cdn.example.com/1.jpg","bio":"Full-stack developer"}}],"pagination":{"total":150,"page":1,"limit":10}}

Can you read this?

After Formatter (Prettified)

{
  "users": [
    {
      "id": 1,
      "name": "John Dev",
      "email": "john@dev.com",
      "profile": {
        "avatar": "https://cdn.example.com/1.jpg",
        "bio": "Full-stack developer"
      }
    }
  ],
  "pagination": {
    "total": 150,
    "page": 1,
    "limit": 10
  }
}

The structure is visible. You can immediately identify where users[0].profile.bio is located.


5 Common JSON Errors

1. Trailing Comma

The most common mistake. It's allowed in JavaScript, but it's an error in JSON.

// Wrong: Unexpected token }
{
  "name": "John Dev",
  "age": 30,
}

// Correct
{
  "name": "John Dev",
  "age": 30
}

2. Single Quotes

// Wrong: Unexpected token '
{'name': 'John Dev'}

// Correct
{"name": "John Dev"}

3. Unquoted Keys

// Wrong: Unexpected token n
{name: "John Dev"}

// Correct
{"name": "John Dev"}

4. Unescaped Characters

// Wrong: newlines, tabs, etc.
{"message": "Hello
World"}

// Correct
{"message": "Hello\nWorld"}
CharacterEscape
Newline\n
Tab\t
Backslash\\
Double quote\"

5. Invalid Number Format

// Wrong
{"value": 007}       // leading zero
{"hex": 0xFF}        // hexadecimal

// Correct
{"value": 7}
{"hex": "0xFF"}      // as string

Practical: Formatting in Code

JavaScript

// Debugging API responses
fetch('/api/users')
  .then(res => res.json())
  .then(data => {
    // Easy to read in console
    console.log(JSON.stringify(data, null, 2));
  });

The third argument of JSON.stringify(data, null, 2):

  • 2: 2-space indentation
  • 4: 4-space indentation
  • '\t': tab indentation

Extracting Specific Fields

const user = {
  id: 1,
  name: "John Dev",
  password: "secret123",
  email: "john@dev.com"
};

// Output without password
console.log(JSON.stringify(user, ['id', 'name', 'email'], 2));

Output:

{
  "id": 1,
  "name": "John Dev",
  "email": "john@dev.com"
}

Working with JSON on the Command Line

jq - The Swiss Army Knife for JSON

# Installation
brew install jq      # macOS
apt install jq       # Ubuntu

# Formatting
cat response.json | jq .

# Extract specific field
cat response.json | jq '.users[0].name'

# Filter arrays
cat response.json | jq '.users[] | select(.age > 30)'

# Select fields into new object
cat response.json | jq '.users[] | {name, email}'

Python

# Validate + format file
python -m json.tool data.json

# Process via pipe
curl https://api.example.com/users | python -m json.tool

Node.js

# Check if file is valid JSON
node -e "require('./data.json')"

Structure Validation with JSON Schema

Beyond simple syntax checking, you can validate data structure and types.

Schema Definition

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

Validation in JavaScript (ajv)

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv();
addFormats(ajv);

const validate = ajv.compile(schema);

const data = {
  name: "John Dev",
  email: "invalid-email",
  age: -5
};

if (!validate(data)) {
  console.log(validate.errors);
  // [
  //   { keyword: 'format', message: 'must match format "email"' },
  //   { keyword: 'minimum', message: 'must be >= 0' }
  // ]
}

IDE/Editor Settings

VSCode

# Auto-format shortcut
Windows/Linux: Shift + Alt + F
Mac: Shift + Option + F

# Auto-format on save (settings.json)
"[json]": {
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

JetBrains (IntelliJ, WebStorm)

# Auto-format
Windows/Linux: Ctrl + Alt + L
Mac: Cmd + Option + L

FAQ

Q: I want to add comments to JSON

A: Standard JSON doesn't support comments. Alternatives:

  1. JSONC (JSON with Comments): Used in VSCode config files, etc.
  2. JSON5: Allows comments, trailing commas, single quotes
  3. Separate field: "_comment": "description"
{
  "_comment": "This configuration is for development",
  "debug": true
}

Q: My large JSON file won't open

A: Regular editors freeze on files of tens of MBs. Alternatives:

  • jq: Streaming processing
  • fx: Terminal interactive viewer (npm i -g fx)
  • Online tools: Dedicated large JSON viewers

Q: Can't I just log the entire API response?

A: It's dangerous in production.

// Wrong: May expose sensitive data
console.log(JSON.stringify(apiResponse));

// Correct: Mask sensitive fields
const sanitize = (obj) => JSON.stringify(obj, (key, val) =>
  ['password', 'token', 'secret'].includes(key) ? '***' : val
);

Summary

SituationSolution
Hard to read API responseUse Formatter for indentation
Parsing errorUse Validator for syntax check
Recurring errorsCheck trailing comma, quotes
Structure validationUse JSON Schema
CLI processingUse jq

Related Tools

ToolPurpose
JSON FormatterFormat/minify
JSON ValidatorSyntax validation
JSON to CSVFormat conversion
JSONformattervalidatorAPIdev toolsdebugging

About the Author

Toolypet Team

Toolypet Team

Development Team

The Toolypet Team creates free, privacy-focused web tools for developers and designers. All tools run entirely in your browser with no data sent to servers.

Web DevelopmentCSS ToolsDeveloper ToolsSEOSecurity