Copynix
Dev Tools7 min read

JSON Best Practices: Formatting, Validation, and Common Pitfalls

JSON is the lingua franca of modern APIs — but subtle formatting errors, security issues, and schema mismatches cause real problems. This guide covers the best practices every developer should know.

T

Nguyễn Văn Thương

Founder, Copynix

JSONAPIvalidation

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data format specified in RFC 8259. It represents data as key-value pairs, arrays, strings, numbers, booleans, and null. Despite originating from JavaScript syntax, JSON is language-independent and is now the default data format for REST APIs, configuration files, and message queues worldwide.

JSON Syntax Fundamentals

A valid JSON document is one of: object, array, string, number, boolean, or null.

{
  "name": "Alice",
  "age": 30,
  "active": true,
  "address": {
    "city": "Berlin",
    "zip": "10115"
  },
  "tags": ["developer", "designer"],
  "notes": null
}

Common syntax rules that trip people up:

Common JSON Parsing Errors and How to Fix Them

Unexpected token

// Invalid — single quotes and trailing comma
{'name': 'Alice', 'age': 30,}

// Valid
{"name": "Alice", "age": 30}

Precision loss with large numbers

JSON numbers map to IEEE 754 double-precision floats in JavaScript. Integers larger than Number.MAX_SAFE_INTEGER (2^53 - 1 = 9,007,199,254,740,991) lose precision:

JSON.parse('{"id": 9007199254740993}')
// → {id: 9007199254740992}  ← precision loss!

For large integers (like database IDs, snowflake IDs), transmit them as strings in JSON and parse them with a BigInt-aware library.

Circular references

const obj = {};
obj.self = obj;
JSON.stringify(obj); // TypeError: Converting circular structure to JSON

Use a replacer function or a library like flatted to handle circular structures.

JSON Schema Validation

JSON Schema (defined at json-schema.org) is a vocabulary for describing the structure of JSON documents. Use it to validate API inputs and catch malformed data early.

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

Validation libraries: ajv (Node.js), jsonschema (Python), networknt/json-schema-validator (Java).

Security Considerations

JSON injection

If user input is embedded directly into a JSON string without proper escaping, an attacker can inject additional JSON fields or corrupt the structure. Always use a proper serialization function (JSON.stringify()) rather than building JSON by string concatenation.

// WRONG — vulnerable to injection if username contains quotes or backslashes
const json = '{"user": "' + username + '"}';

// CORRECT
const json = JSON.stringify({ user: username });

Prototype pollution

Parsing JSON that contains __proto__ or constructor keys can pollute JavaScript object prototypes in some libraries:

// Dangerous with vulnerable parsers
JSON.parse('{"__proto__": {"isAdmin": true}}')

Use libraries that are prototype-pollution safe, or sanitize keys after parsing in security-sensitive contexts.

Large payload DoS

Deeply nested or very large JSON payloads can cause stack overflows or excessive memory use during parsing. Set maximum payload sizes in your HTTP framework (express.json({ limit: "1mb" })) and consider depth limits for untrusted inputs.

API Design Best Practices

Formatting and Minification

Use pretty-printed JSON during development for readability, minified JSON in production for smaller payloads:

// Pretty (development)
JSON.stringify(obj, null, 2);

// Minified (production)
JSON.stringify(obj);

Use the Copynix JSON Formatter to instantly format and validate JSON in your browser. It highlights syntax errors, supports pretty-print and minify modes, and handles large payloads without sending any data to a server.

JSON Alternatives Worth Knowing

Summary

JSON is simple by design, but its edge cases (large numbers, circular references, security pitfalls) create real bugs in production systems. Validate API inputs with JSON Schema, serialize with JSON.stringify() (never string concatenation), set payload limits, and use ISO 8601 for dates. These practices catch the majority of JSON-related bugs before they reach users.

Free tool

Try it yourself — JSON Formatter

Runs entirely in your browser. No signup, no data sent to servers.

Open JSON Formatter
T

Nguyễn Văn Thương

Founder & Developer · Copynix

Software developer focused on web security and developer tooling. Built Copynix to provide privacy-respecting browser tools that never send your data to a server.

More about the author →

Keep Reading

All articles →
All articlesBrowse tools →