Developer

JSON Formatter: How to Format and Validate JSON Online

HR
Hassaan Rasheed
· August 29, 2026 10 min read
JSON Formatter: How to Format and Validate JSON Online

You paste an API response into your editor and get a single unbroken line: {"user":{"id":1,"name":"Hassan","roles":["admin","editor"],"settings":{"theme":"dark","notifications":true}}}. You need to check a specific nested value but the entire structure is compressed with no line breaks or spacing. Reading it means scanning left to right through one long string, counting braces mentally as you go.

The JSON Formatter at ToolCenterHub converts minified JSON into indented, readable output in your browser. Paste your JSON, click format, and the structure becomes visible with nesting levels clearly shown. This guide covers what JSON formatting does, the exact syntax rules that cause parse errors, how to read the error messages the browser gives you when JSON is invalid, and how to format JSON without an online tool when you are working in a terminal or code editor.

What Is JSON and Why Does Formatting Matter?

JSON stands for JavaScript Object Notation. It is a text-based format for representing structured data that was derived from JavaScript object syntax but is now language-independent. Every major programming language has a JSON parser built in or available as a standard library.

JSON represents four primitive types: strings (always in double quotes), numbers, booleans (true or false), and null. It represents two structured types: objects (key-value pairs wrapped in curly braces) and arrays (ordered lists wrapped in square brackets). Every key in a JSON object must be a string wrapped in double quotes. These rules are strict and non-negotiable in standard JSON.

Formatting matters for one practical reason: the JSON that APIs send in production is minified. Whitespace is removed because smaller payloads mean faster transfers and lower bandwidth costs. A response that contains user data, pagination metadata, and nested settings objects can easily be 2,000 characters long when compressed into one line. That same response formatted with 2-space indentation might span 80 readable lines.

For developers debugging an integration, building a parser, or inspecting an unfamiliar API, the prettified version shows the structure at a glance. You can see which fields are nested inside which objects, whether an array contains 3 items or 30, and whether a value is a string, a number, or a nested object, all without counting brackets manually. API responses commonly include UUID identifiers and hash values as string fields. Formatted output makes these easy to locate and copy without scanning a single compressed line.

Formatting is also the first step in spotting malformed JSON. When a response is one unbroken line, a missing closing bracket or an extra comma is nearly invisible. When the same JSON is formatted and the parser rejects it, the error message tells you exactly which character caused the failure.

How Does a JSON Formatter Work?

A JSON formatter does two things: it parses the input string and re-serializes it with indentation. In JavaScript, the full operation is two function calls: JSON.parse(inputString) followed by JSON.stringify(parsedObject, null, 2). The second argument to JSON.stringify is a replacer function (null means no replacement). The third argument is the indentation level, here 2 spaces per level.

The result is the same data, re-serialized with consistent line breaks and indentation. No information is added or removed. Values stay the same. Nesting relationships stay the same.

One technical note: JSON objects are technically unordered collections of key-value pairs. The JSON specification does not guarantee key order. In practice, most modern JavaScript engines preserve insertion order when parsing and re-serializing, so the output order usually matches the input order. But this is not something you can rely on if key order matters for your use case.

Online formatters run this process in your browser, which means your data stays on your machine. They also add a validation step: if JSON.parse() throws a SyntaxError, the formatter shows you the error message and the position of the failure rather than silently producing empty output.

What a formatter does in order:

  1. Receives the input string from the text area
  2. Calls JSON.parse() to convert it to a JavaScript object or array
  3. If parsing fails, displays the SyntaxError message and character position
  4. If parsing succeeds, calls JSON.stringify() with 2-space indentation
  5. Displays the prettified string in the output area

JSON Syntax Rules That Trip Developers Up

JSON has stricter syntax than JavaScript object notation. Most parse errors come from writing JSON the way you would write a JavaScript object, which is close but not identical.

In practice, trailing commas account for the majority of JSON parse failures in real integration work. Missing quotes and undefined values get caught earlier, by editors and linters, before JSON reaches a parser. Trailing commas survive those checks because they are valid JavaScript syntax, and many style guides actively encourage them for cleaner diffs.

Double quotes only. All string values and all key names must use double quotes. Single quotes are not valid JSON. {'name': 'Hassan'} is valid JavaScript object syntax but invalid JSON. {"name": "Hassan"} is valid JSON.

No trailing commas. The last item in an object or array cannot have a comma after it. {"a": 1, "b": 2,} fails. {"a": 1, "b": 2} is valid. This is the most common mistake when hand-editing JSON because many code style guides encourage trailing commas in JavaScript for cleaner diffs.

No comments. JSON does not support // single-line comments or /* */ block comments. If you paste a JSON configuration file that contains inline comments, it will fail to parse. Use JSON5 if you need comments, but be aware it requires a dedicated parser.

Quoted key names. JavaScript allows {name: "Hassan"} with an unquoted key. JSON requires {"name": "Hassan"}. Every key must be a string in double quotes.

Strict number format. Numbers cannot start with a leading zero. 01 is not valid but 1 is. Infinity and NaN are not valid JSON values. Hexadecimal notation like 0x1F is not valid.

Null, not undefined. JavaScript has both null and undefined. JSON only recognizes null. If you call JSON.stringify() on an object that has undefined values, those keys are silently dropped from the output, which can cause unexpected missing fields.

Escaped characters in strings. If a string value contains a double quote, backslash, or control character, it must be escaped with a backslash. A literal newline inside a string value is not valid JSON. Use the escape sequence \n instead. String values that contain Base64-encoded data appear as long strings of letters, numbers, and +, /, = characters. These are valid JSON strings, not encoding errors.

What Do JSON Error Messages Mean and How Do You Fix Them?

When JSON.parse() fails, the browser throws a SyntaxError. The message tells you what the parser encountered at the point of failure, not always why. This table maps the most common error messages to their causes and fixes:

Error MessageCauseFix
Unexpected token '}'Trailing comma before a closing braceRemove the comma after the last key-value pair in the object
Unexpected token ']'Trailing comma before a closing bracketRemove the comma after the last item in the array
Unexpected token "'"Single quotes used instead of double quotesReplace all single quotes wrapping keys or values with double quotes
Unexpected token '/'Comment in the JSONRemove the comment entirely or move it to a separate file
Unexpected token 'k' (or any letter)Unquoted key nameWrap the key name in double quotes
Unexpected end of JSON inputIncomplete JSON, usually a truncated string or unclosed bracketCheck for missing closing } or ] at the end
Unexpected token 'u'The word undefined used as a valueReplace undefined with null
Unexpected token 'T'Boolean written as True instead of trueUse lowercase true, false, and null
Unexpected numberLeading zero on a number, such as 07Remove the leading zero
Bad escaped characterAn unescaped special character inside a stringEscape it: \" for quote, \\ for backslash, \n for newline

The most useful debugging step when you get a SyntaxError is to look at the character position the error reports. Most browser engines include text like "at position 142" in the error message. Count to that position in your JSON string. The problem is directly at that character or one character before it.

A split-screen view showing minified JSON on the left as a single dense line of text and prettified JSON on the right with 2-space indentation, both showing the same user object with name, email, roles array, and nested settings object, displayed against a dark code editor background

How to Format JSON Without an Online Tool

When you are working in a terminal, a CI pipeline, or a restricted environment without browser access, these tools format JSON from the command line or within your editor. The developer tools section has additional utilities for related formats like URL encoding and Base64 that often appear alongside JSON in API work:

jq (command line): jq is a lightweight JSON processor available on Linux, Mac, and Windows. The command cat file.json | jq . prints prettified JSON to the terminal. echo '{"a":1}' | jq . works inline. jq also supports filtering, so cat file.json | jq '.user.email' extracts a specific value directly. For repeated command-line JSON work, jq is worth installing once and keeping permanently. The filter syntax takes an hour to learn and covers formatting, value extraction, and structure transformation in a single command; the browser console and Python one-liners require retyping on every use.

Node.js (one-liner): node -e "process.stdin.resume(); let d=''; process.stdin.on('data',c=>d+=c); process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))" reads JSON from stdin and prints prettified JSON. More practically, a short script file handles this cleanly.

Python (built-in): python -m json.tool file.json formats a JSON file and prints the result to the terminal. Works with Python 2 and Python 3. python -m json.tool --indent 2 file.json specifies 2-space indentation.

VS Code: Open a .json file and press Shift+Alt+F on Windows or Shift+Option+F on Mac to format the document. VS Code uses the built-in JSON language server which formats and validates simultaneously. Any syntax errors appear as red underlines before you format.

Browser console: Paste JSON.stringify(JSON.parse('your json here'), null, 2) into the browser developer console and press Enter. If the JSON is valid, you get the formatted output. If it is invalid, you get the SyntaxError message with the position.

Minified vs. Prettified vs. Validated: Three Different Operations

These terms describe different operations that JSON tools combine under the label "formatter":

Minification removes all whitespace characters from JSON. The output is the most compact representation of the data. Minified JSON is what APIs send in production. Use minification before sending JSON in a request body to reduce payload size.

Prettification adds consistent indentation and line breaks. The data is identical to the minified version but formatted for reading. This is what the formatter produces as its primary output.

Validation checks whether the input can be parsed as valid JSON at all. Validation does not format the output. You can validate minified JSON without changing its whitespace. Validation fails when there is a syntax error. Validation passes when the JSON is structurally correct, regardless of indentation style.

A complete online JSON formatter like the JSON Formatter does all three on a single paste: it validates the input, formats the valid JSON, and also offers the option to copy the minified version. Tools that only prettify without validating can produce misleading output if the input has a subtle syntax error that the formatter silently ignores.

The most important thing to understand about JSON formatting is that it changes nothing about the data, only the whitespace. A minified JSON response and its prettified counterpart are semantically identical. When an API integration produces unexpected results, format the raw response first and read the structure before assuming the problem is in your code. Most JSON bugs are visible immediately once the structure is readable.

Frequently Asked Questions

JSON formatting converts minified or compressed JSON text into indented, readable output with each key-value pair on its own line. An unformatted API response arrives as a single continuous string. A formatter adds line breaks and consistent indentation so the structure becomes visible. Formatting does not change the data itself. The keys, values, and nesting are identical before and after. Only whitespace changes.

JSON parse errors come from specific syntax violations: trailing commas after the last item in an array or object, single quotes instead of double quotes around strings or key names, JavaScript-style comments that JSON does not allow, unquoted key names, and numeric values that start with a leading zero. Each violation produces a SyntaxError with a message identifying the character position where parsing stopped.

Standard JSON does not support comments. Neither // single-line comments nor block comments are valid JSON syntax. Attempting to parse JSON that contains comments produces a SyntaxError. JSON5 is an unofficial extension that allows comments and trailing commas, but it requires a separate parser and is not compatible with JSON.parse() in browsers or most API endpoints that expect standard JSON.

JSON requires all key names to be wrapped in double quotes. JavaScript object syntax allows unquoted keys and single-quoted string values. JSON does not allow trailing commas after the last item. JSON does not allow undefined, functions, Symbol, or Date objects as values. A JavaScript object is in-memory data. JSON is a serialized text format for transmitting data. JSON.stringify() converts an object to JSON text and JSON.parse() converts JSON text back to an object.

In any browser developer console, run JSON.parse() and paste your JSON as a string argument. If the JSON is valid it returns the parsed object. If invalid it throws a SyntaxError with the position of the error. In Node.js the same method works. In VS Code, files with a .json extension are validated automatically and syntax errors are underlined. Most REST clients like Postman also validate JSON response bodies automatically.

HR

Written by

Hassaan Rasheed

Builder of ToolCenterHub. Passionate about creating fast, privacy-first tools that anyone can use without friction, accounts, or paywalls. Writing about design, development, and the web.

Connect on LinkedIn