ToolPopToolPop
Back to BlogGuides

JSON Formatting and Validation: Complete Developer Guide 2025

JSON is the backbone of modern web development. Master formatting, validation, and best practices with this comprehensive guide.

ToolPop TeamMarch 12, 202516 min read

Understanding JSON: The Universal Data Format

JSON (JavaScript Object Notation) has become the de facto standard for data exchange in web applications, APIs, configuration files, and more. Despite its simplicity, developers often encounter issues with JSON formatting and validation.

This comprehensive guide covers everything you need to know about working with JSON effectively.

JSON Syntax Fundamentals

Basic Structure

JSON supports six data types:

  • Strings: Text enclosed in double quotes
  • Numbers: Integers or floating-point
  • Booleans: true or false
  • Null: Empty value represented as null
  • Objects: Key-value pairs in curly braces
  • Arrays: Ordered lists in square brackets

JSON Object Example

{
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]",
  "isActive": true,
  "balance": null,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zipCode": "10001"
  },
  "hobbies": ["reading", "coding", "travel"]
}

Syntax Rules

JSON has strict syntax rules that must be followed:

  • Keys must be strings: Always use double quotes
  • No trailing commas: The last item cannot have a comma
  • Double quotes only: Single quotes are not valid
  • No comments: JSON doesn't support comments
  • No undefined: Use null instead

Valid vs. Invalid JSON

// VALID JSON
{
  "name": "John",
  "age": 30
}

// INVALID - single quotes
{
  'name': 'John'
}

// INVALID - trailing comma
{
  "name": "John",
  "age": 30,
}

// INVALID - unquoted key
{
  name: "John"
}

// INVALID - comments
{
  "name": "John"  // This is a comment
}

Common JSON Errors and How to Fix Them

Error 1: Unexpected Token

SyntaxError: Unexpected token } at position 45

Cause: Usually a missing comma or extra comma

Example problematic JSON:

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

Fix: Add missing comma:

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

Error 2: Unexpected End of Input

SyntaxError: Unexpected end of JSON input

Cause: Unclosed brackets, braces, or quotes

Example:

{
  "name": "John",
  "hobbies": ["reading", "coding"
}

Fix: Close all brackets:

{
  "name": "John",
  "hobbies": ["reading", "coding"]
}

Error 3: Invalid Character

SyntaxError: Bad control character in string

Cause: Unescaped special characters

Example:

{
  "path": "C:\Users\John"
}

Fix: Escape backslashes:

{
  "path": "C:\\Users\\John"
}

Error 4: Invalid Number

SyntaxError: Invalid number

Cause: Incorrectly formatted numbers

Examples of invalid numbers:

{
  "value1": .5,      // Missing leading zero
  "value2": 1.,      // Trailing decimal
  "value3": 0x1F,    // Hexadecimal not allowed
  "value4": NaN,     // Not a valid JSON number
  "value5": Infinity // Not a valid JSON number
}

Fix: Use valid number formats:

{
  "value1": 0.5,
  "value2": 1.0,
  "value3": 31,
  "value4": null,
  "value5": null
}

JSON Formatting Best Practices

Consistent Indentation

Use consistent indentation (2 or 4 spaces):

{
  "user": {
    "name": "John",
    "email": "[email protected]",
    "roles": [
      "admin",
      "user"
    ]
  }
}

Logical Key Ordering

Order keys logically or alphabetically:

{
  "id": 1,
  "name": "Product Name",
  "description": "Product description",
  "price": 29.99,
  "category": "Electronics",
  "inStock": true,
  "createdAt": "2025-01-15T10:30:00Z",
  "updatedAt": "2025-03-01T14:45:00Z"
}

Meaningful Key Names

Use descriptive, camelCase key names:

// Good
{
  "firstName": "John",
  "lastName": "Doe",
  "emailAddress": "[email protected]",
  "phoneNumber": "+1-555-0100"
}

// Avoid
{
  "fn": "John",
  "ln": "Doe",
  "e": "[email protected]",
  "p": "+1-555-0100"
}

Date Formatting

Use ISO 8601 format for dates:

{
  "createdAt": "2025-03-15T14:30:00Z",
  "scheduledFor": "2025-04-01T09:00:00-05:00",
  "dateOnly": "2025-03-15"
}

JSON in Different Contexts

API Responses

{
  "success": true,
  "data": {
    "users": [
      {
        "id": 1,
        "name": "John Doe",
        "email": "[email protected]"
      }
    ],
    "pagination": {
      "page": 1,
      "perPage": 10,
      "total": 100,
      "totalPages": 10
    }
  },
  "meta": {
    "requestId": "abc123",
    "timestamp": "2025-03-15T14:30:00Z"
  }
}

Configuration Files

{
  "app": {
    "name": "MyApplication",
    "version": "1.0.0",
    "port": 3000
  },
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp_db"
  },
  "logging": {
    "level": "info",
    "format": "json"
  }
}

Package.json Example

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "A sample project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest",
    "build": "webpack"
  },
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "jest": "^29.7.0",
    "webpack": "^5.89.0"
  }
}

JSON Manipulation in JavaScript

Parsing JSON

// Parse JSON string to object
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"

// Handle parsing errors
try {
  const data = JSON.parse(invalidJson);
} catch (error) {
  console.error('Invalid JSON:', error.message);
}

Stringifying Objects

// Convert object to JSON string
const obj = { name: "John", age: 30 };

// Minified
const minified = JSON.stringify(obj);
// {"name":"John","age":30}

// Pretty printed with 2 spaces
const pretty = JSON.stringify(obj, null, 2);
/*
{
  "name": "John",
  "age": 30
}
*/

// With custom replacer
const filtered = JSON.stringify(obj, ['name']);
// {"name":"John"}

Deep Cloning with JSON

// Simple deep clone (with limitations)
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));

// Note: This method doesn't work with:
// - Functions
// - undefined values
// - Dates (become strings)
// - RegExp
// - Map/Set
// - Circular references

JSON vs. Other Data Formats

JSON vs. XML

FeatureJSONXML
ReadabilityHighMedium
File SizeSmallerLarger
Parsing SpeedFasterSlower
Data TypesNativeAll strings
Schema SupportJSON SchemaXSD
CommentsNoYes

JSON vs. YAML

FeatureJSONYAML
SyntaxStrictFlexible
CommentsNoYes
Multiline StringsEscapedNative
Anchors/AliasesNoYes
Human EditingGoodBetter
Machine ParsingEasyComplex

JSON vs. TOML

FeatureJSONTOML
Config FilesGoodBetter
Nested DataGoodLimited
CommentsNoYes
DatesStringsNative
Arrays of TablesAwkwardNative

Advanced JSON Techniques

JSON Schema Validation

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

JSON Path Queries

Query JSON data using JSONPath:

$.store.book[*].author          // All authors
$.store.book[?(@.price < 10)]   // Books under $10
$..author                        // All authors anywhere
$.store.book[0]                  // First book
$.store.book[-1]                 // Last book

JSON Patch

Describe changes to JSON documents:

[
  { "op": "add", "path": "/email", "value": "[email protected]" },
  { "op": "remove", "path": "/oldField" },
  { "op": "replace", "path": "/name", "value": "Jane Doe" },
  { "op": "move", "from": "/old", "path": "/new" }
]

Working with Large JSON Files

Streaming Parsers

For large files, use streaming parsers:

// Node.js with JSONStream
const JSONStream = require('JSONStream');
const fs = require('fs');

fs.createReadStream('large-file.json')
  .pipe(JSONStream.parse('data.*'))
  .on('data', (item) => {
    // Process each item
    console.log(item);
  });

Memory Optimization

Tips for handling large JSON:

  • Stream instead of loading entirely
  • Process in chunks
  • Use pagination for API responses
  • Consider binary formats (MessagePack, BSON)

Security Considerations

JSON Injection Prevention

// Dangerous - allows injection
const userInput = '"; console.log("hacked"); "';
const dangerous = \`{"name": "\${userInput}"}\`;

// Safe - use JSON.stringify
const safe = JSON.stringify({ name: userInput });

Prototype Pollution

// Vulnerable parsing
const obj = JSON.parse('{"__proto__": {"isAdmin": true}}');

// Safe parsing with null prototype
const safeObj = Object.create(null);
Object.assign(safeObj, JSON.parse(jsonString));

Tools and Resources

Online Tools

  • ToolPop JSON Formatter: Format, validate, and minify JSON
  • JSON Schema Validator: Validate JSON against schemas
  • JSONPath Evaluator: Test JSONPath queries

VS Code Extensions

  • Prettier - Code formatter
  • JSON Tools - Format and minify
  • JSON Schema - Validation support

Command Line Tools

# jq - JSON processor
cat file.json | jq '.'

# Python json.tool
python -m json.tool file.json

# Node.js
node -e "console.log(JSON.stringify(require('./file.json'), null, 2))"

Conclusion

Mastering JSON is essential for modern web development. Understanding its syntax, common pitfalls, and best practices will make you a more effective developer.

Key takeaways:

  • JSON has strict syntax rules—learn them
  • Use proper formatting for readability
  • Validate JSON before processing
  • Handle errors gracefully
  • Consider security implications
Use ToolPop's free JSON Formatter to validate and format your JSON instantly!

Tags
json formattingjson validationjson beautifyjson minifyjson syntaxjson errors
Share this article

Try Our Free Tools

Put these tips into practice with our free online tools. No signup required.

Explore Tools