How to Validate and Format JSON Like a Pro

If you have ever copied a JSON response from an API, pasted it into a config file, or tried to debug a webhook payload, you have almost certainly run into broken JSON at some point. A missing comma, an extra trailing bracket, or an unescaped quote character can turn a perfectly good data structure into an inscrutable error message. The good news is that validating and formatting JSON is a skill you can master quickly — and it will save you countless hours of frustration.

This guide covers everything you need to know about working with JSON effectively: what JSON actually is, the most common mistakes developers make, how to validate and format it properly, and the best practices for using JSON in production APIs.

What Is JSON?

JSON stands for JavaScript Object Notation. Despite the name, JSON is language-independent — it is used by virtually every modern programming language as a lightweight data interchange format. JSON was formalized by Douglas Crockford in the early 2000s and is defined by RFC 8259.

At its core, JSON represents data using two universal structures:

  • Objects — Unordered collections of key-value pairs, wrapped in curly braces {}. Keys must be strings enclosed in double quotes.
  • Arrays — Ordered lists of values, wrapped in square brackets [].

Values in JSON can be strings, numbers, booleans (true or false), null, objects, or arrays. That is the entire specification — JSON's simplicity is precisely what makes it so powerful and widely adopted.

Here is a well-formed JSON example representing a user profile:

{
  "name": "Alice Chen",
  "email": "[email protected]",
  "age": 29,
  "isVerified": true,
  "roles": ["admin", "editor"],
  "address": {
    "city": "San Francisco",
    "state": "CA",
    "zip": "94105"
  }
}

Common JSON Syntax Errors

Even experienced developers make JSON syntax mistakes regularly, especially when editing JSON by hand. Here are the errors you will encounter most often and how to recognize them:

1. Trailing Commas

This is probably the single most common JSON error. In JavaScript, trailing commas in arrays and objects are perfectly legal. In JSON, they are not. A trailing comma after the last item will cause any JSON parser to reject the entire document.

// INVALID — trailing comma after "editor"
{
  "roles": ["admin", "editor",]
}

// VALID
{
  "roles": ["admin", "editor"]
}

2. Single Quotes Instead of Double Quotes

JSON requires double quotes for all strings and keys. Single quotes, backticks, and unquoted keys are not valid JSON, even though they work fine in JavaScript objects.

// INVALID — single quotes and unquoted key
{name: 'Alice'}

// VALID
{"name": "Alice"}

3. Missing or Extra Brackets

When JSON documents are deeply nested, it is easy to lose track of opening and closing brackets. A missing } or ] will produce a parse error, and the error message from most parsers points to the end of the document rather than where the bracket was actually missing. This is where a good formatter with bracket matching becomes invaluable.

4. Unescaped Special Characters

Strings in JSON must escape certain characters: double quotes (\"), backslashes (\\), and control characters like newlines (\n) and tabs (\t). Pasting raw text that contains these characters without escaping them will break the JSON structure.

// INVALID — unescaped quote inside string
{"message": "She said "hello""}

// VALID
{"message": "She said \"hello\""}

5. Comments

JSON does not support comments. No single-line // comments, no multi-line /* */ comments. If you need configuration files with comments, consider formats like JSON5 or JSONC (used by VS Code), but be aware that standard JSON parsers will reject them. This catches many developers off guard when they try to annotate their configuration files.

How to Validate JSON

Validating JSON means checking that a string conforms to the JSON specification and can be parsed without errors. There are several approaches, depending on your context:

In Your Code

Every major language has a built-in JSON parser, and attempting to parse the string is the simplest form of validation:

  • JavaScript: JSON.parse(str) throws a SyntaxError if the input is not valid JSON.
  • Python: json.loads(str) raises a json.JSONDecodeError with a helpful line and column number.
  • Java: Libraries like Jackson or Gson will throw exceptions on malformed input.
  • Go: json.Unmarshal() returns an error describing the exact issue.

For structural validation beyond syntax — ensuring that a JSON document has the right fields, types, and constraints — use JSON Schema. JSON Schema lets you define a blueprint for your data and validate documents against it. This is particularly useful for API request/response validation, where you want to catch missing required fields or incorrect types before they cause bugs downstream.

Using an Online Tool

When you are debugging a quick issue or working with a one-off payload, an online validator is the fastest option. A good tool will parse your JSON, highlight the exact location of any errors, and let you format the result for readability. TensorLocal's JSON Formatter & Validator does exactly this — paste your JSON, and it instantly validates the structure, highlights errors with line numbers, and lets you beautify or minify the output with one click.

Try our free JSON Formatter & Validator — instant validation with syntax highlighting and error detection.

Open JSON Formatter →

How to Format JSON for Readability

Raw JSON from APIs and logs often arrives as a single compressed line. While this is efficient for transmission, it is nearly impossible for a human to read. Formatting (also called "pretty-printing" or "beautifying") adds consistent indentation and line breaks so you can quickly scan the structure.

Most languages provide a built-in formatting option:

// JavaScript
JSON.stringify(obj, null, 2);

// Python
json.dumps(obj, indent=2, ensure_ascii=False)

// Command line with jq
echo '{"a":1,"b":[2,3]}' | jq .

The 2 in these examples refers to the number of spaces per indentation level. Two spaces is the most common convention, but four spaces and tabs are also used. The important thing is consistency within a project.

Conversely, when you need to send JSON over a network or store it efficiently, minification removes all unnecessary whitespace. This can meaningfully reduce payload sizes, especially for large documents. A 500-line formatted JSON config file might shrink by 30–40% when minified.

JSON Best Practices for APIs

If you are designing an API that uses JSON, following established conventions will make your API easier to consume and less error-prone for your users:

Use Consistent Naming Conventions

Pick a casing style for your keys and stick with it throughout your entire API. camelCase (e.g., firstName) is the most common in JavaScript ecosystems. snake_case (e.g., first_name) is standard in Python and Ruby APIs. Mixing styles within the same API is confusing and signals poor attention to detail.

Use Appropriate Data Types

Do not encode numbers or booleans as strings unless there is a specific reason. A field like "age": "29" forces every consumer to parse the string into a number, which introduces unnecessary complexity and potential for bugs. Use native JSON types: "age": 29, "active": true, "deletedAt": null.

Handle Null and Missing Fields Intentionally

There is a meaningful difference between a field being null (explicitly no value) and a field being absent (not applicable or unknown). Document your API's behavior clearly. Many teams adopt the convention that null means "this field exists but has no value" while omission means "this field is not relevant to this response."

Return Consistent Error Structures

When your API encounters an error, return a JSON object with a predictable structure. At a minimum, include an error code and a human-readable message. Consider adopting a standard format like RFC 7807 (Problem Details):

{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation Error",
  "status": 422,
  "detail": "The 'email' field must be a valid email address.",
  "instance": "/users/register"
}

Paginate Large Collections

Never return unbounded arrays from an API endpoint. Use pagination with clear metadata so clients know how to fetch subsequent pages:

{
  "data": [ ... ],
  "pagination": {
    "page": 1,
    "perPage": 20,
    "totalItems": 347,
    "totalPages": 18
  }
}

Debugging JSON: A Practical Workflow

When you receive a JSON parse error and the data looks correct at first glance, follow this systematic approach:

  1. Paste it into a validator. A good formatter will pinpoint the exact line and character position of the error. TensorLocal's JSON Formatter highlights the error location in the output.
  2. Check for invisible characters. Copy-pasting from rich text editors, PDFs, or messaging apps can introduce invisible Unicode characters (like zero-width spaces or non-breaking spaces) that break parsers. If the JSON looks correct but will not parse, try retyping the problematic section manually.
  3. Validate encoding. JSON must be encoded as UTF-8 (or UTF-16/32, though UTF-8 is overwhelmingly dominant). If you see garbled characters or unexpected escape sequences, check that the source and consumer agree on the encoding.
  4. Look for truncation. If the error points to the end of the document, the JSON may have been truncated during transmission. Check network logs or storage limits.
  5. Diff against a known-good version. If you are editing a JSON config and something broke, use a diff tool to compare your changes against the last working version.

Beyond Basic JSON: Related Formats

As JSON has grown in popularity, several variants and extensions have emerged to address its limitations:

  • JSON5 — Extends JSON with features like comments, trailing commas, single-quoted strings, and unquoted keys. Useful for configuration files where human editability matters more than strict interoperability.
  • JSONC — JSON with Comments. Used by VS Code and TypeScript for configuration files. Allows single-line and multi-line comments while keeping everything else standard.
  • JSON Lines (JSONL) — Each line of the file is a separate, complete JSON object. Ideal for log files, streaming data, and large datasets because you can process the file line by line without loading everything into memory.
  • JSON Schema — A vocabulary for annotating and validating JSON documents. Defines the structure, required fields, value types, and constraints of your data in a machine-readable way.

Conclusion

JSON's simplicity is its greatest strength, but that simplicity also means there is no room for ambiguity — a single misplaced character will break your data. By understanding the common pitfalls, using a reliable validator, and following consistent API design practices, you can work with JSON confidently and efficiently.

The next time you are staring at a wall of unformatted JSON, remember: you do not have to squint. Paste it into a proper formatter, let the tool do the heavy lifting, and get back to the work that actually matters.