← Back to blog

JSON Formatting: Pretty Print, Validate and Fix Errors

November 8, 2026
JSON Formatting: Pretty Print, Validate and Fix Errors

JSON formatting means adding indentation and line breaks to compact JSON so a person can read it, and checking at the same time that the text is valid. The quickest route is to paste it into a browser-based formatter. In code, use JSON.stringify(value, null, 2) in JavaScript or json.dumps(obj, indent=2) in Python. This guide covers all three, then shows how to fix the errors that stop JSON from formatting.

Pingfloat
pingfloat.com
Format and Validate JSON Quickly
Use Pingfloat’s JSON Formatter to check your data and make valid JSON easier to read, right in your browser.
Format your JSON

TL;DR

  • Formatting changes only whitespace. The data stays the same, and a formatter doubles as a validity check because invalid JSON cannot be parsed.
  • For a quick job, paste the text into a formatter such as the Pingfloat JSON Formatter. For code, use JSON.stringify(value, null, 2) or json.dumps(obj, indent=2).
  • Most "unexpected token" errors come from trailing commas, single quotes, comments, leading zeros or JavaScript-only values.
  • Very large numbers can lose precision in JavaScript, and untrusted JSON can be expensive to parse, so handle both on purpose.

Table of Contents

What JSON formatting actually does

Most JSON in the wild is minified. An API returns one long line with no spaces, which is efficient for machines and miserable for people. Formatting, also called pretty printing or beautifying, re-emits the same data with each nested level indented and each key on its own line.

Here is the same payload both ways:

{"user":{"id":42,"tags":["admin","beta"],"active":true}}
{
  "user": {
    "id": 42,
    "tags": [
      "admin",
      "beta"
    ],
    "active": true
  }
}

Nothing about the data changed. JSON's own specification allows whitespace between tokens, which is why a formatter is free to add it or strip it without altering the meaning.

That has a practical consequence. To pretty print, a tool must first parse your text. If the text is not valid JSON, parsing fails and nothing gets formatted. So "format JSON" and "validate JSON" are really one job, and the error message you get when formatting fails is your best clue about what is wrong.

JSON parsing, validation, and formatting flow

The rules JSON enforces

Before fixing errors, it helps to know what valid JSON allows. According to json.org, JSON is a text format built on two structures: collections of name/value pairs and ordered lists of values. A value can be a string, a number, true, false, null, an object or an array. Objects use braces, arrays use brackets.

The rules that catch people out:

  • Strings use double quotes. Single quotes are not JSON. Special characters are escaped with a backslash.
  • Numbers are plain decimal. JSON numbers do not use octal or hexadecimal notation, per json.org.
  • No comments. MDN's JSON guide notes that comments are not allowed.
  • No JavaScript-only values. undefined, NaN and Infinity have no JSON equivalent.
  • No trailing commas. The last item in an object or array must not be followed by a comma.

If you come from JavaScript, the confusion is understandable. JSON looks like a JavaScript object literal, but it is a stricter text format. A JavaScript object can have unquoted keys, single-quoted strings and a trailing comma. JSON can have none of those.

How to format JSON in a browser

There are two sensible ways to format JSON without installing anything.

Use an online formatter

Paste the text into a formatter, click format and read the result. A good one also tells you where parsing failed. You can do this with our JSON formatter, validator and beautifier, which needs no installation and no account for core use. It suits the everyday cases: an API response copied from your network tab, a config file someone pasted into chat, a webhook payload from a log.

Use the browser console

Every major browser has a JavaScript console, and MDN's Working with JSON guide shows how to use it to call JSON.stringify and inspect the returned string. To pretty print a string you already have, parse it first and then stringify it with indentation:

const raw = '{"a":1,"b":[2,3]}';
console.log(JSON.stringify(JSON.parse(raw), null, 2));

If raw is invalid, the first step throws a SyntaxError, which doubles as your validation. This works well for small snippets. For anything long, a dedicated formatter is easier to scroll, copy and share.

Pretty print JSON in JavaScript and Python

When formatting is part of a script, a test or a logging step, use the language's own library.

JavaScript

MDN documents the third argument of JSON.stringify() as the space parameter, which controls the whitespace used for readability. Pass a number for that many spaces, or a string for custom indentation:

JSON.stringify(value, null, 2);   // two spaces
JSON.stringify(value, null, "\t"); // tabs

The middle argument is a replacer, which can filter or transform properties. Passing null means "keep everything".

Two failure modes are worth knowing. MDN says JSON.stringify can throw a TypeError for circular references and for BigInt values. These are serialization problems with your data, not malformed text, so the fix is to change the object (break the cycle, convert the BigInt to a string), not to edit JSON.

Python

Python's standard json module does the same job. A positive integer for indent gives that many spaces per nesting level:

import json
print(json.dumps(obj, indent=2))

The documentation also lists two options that matter for readable output. sort_keys=True sorts object keys, which makes diffs between two payloads far easier to read. ensure_ascii=False writes non-ASCII characters as they are instead of escaping them, which helps if your data contains names or text in other languages.

On the command line, Python's module also runs as a tool, so python -m json.tool file.json prints a formatted version of a file. It is handy on a server where you cannot open a browser.

Quick comparison

MethodBest forValidates input?
Online formatterOne-off checks, sharing a readable copyYes, reports the parse error
Browser consoleSmall snippets while debugging a pageYes, via JSON.parse
JSON.stringify(value, null, 2)Formatting inside JavaScript codeOnly if you parse first
json.dumps(obj, indent=2)Formatting inside Python codeOnly if you load first

Fix invalid JSON and "unexpected token" errors

An "unexpected token" message means the parser reached a character that cannot appear at that position. The wording varies by browser and runtime, but the causes are few. MDN's page on the JSON.parse bad parsing error lists the usual suspects: trailing commas, single-quoted property names, leading zeros and a decimal point with no digits after it.

What you wroteWhy it failsFix
{"foo": 1, }Trailing commaRemove the last comma
[1, 2, 3, 4, ]Trailing comma in an arrayRemove the last comma
{'name': 'Ana'}Single quotesUse double quotes for keys and strings
{"zip": 02134}Leading zeroWrite 2134, or make it a string "02134" if the zero matters
{"ratio": 5.}Decimal point with no digitsWrite 5.0 or 5
{"a": undefined}Not a JSON valueUse null or leave the key out
{"a": 1 // note}Comments are not allowedDelete the comment

MDN's own examples show JSON.parse('[1, 2, 3, 4, ]') and JSON.parse('{"foo": 1, }') throwing a SyntaxError, so trailing commas really are rejected by the standard parser.

A repeatable way to fix a broken document

  1. Read the position in the error. Many parsers report a line and column or a character offset. Start there, but remember the real mistake is often just before it, such as a missing comma on the previous line.
  2. Check quotes first. Single quotes and unescaped double quotes inside a string cause a large share of failures.
  3. Remove trailing commas and comments. These come from hand-edited config files and from copying JavaScript object literals.
  4. Fix numbers. Look for leading zeros and a bare decimal point.
  5. Replace non-JSON values. Swap undefined, NaN and Infinity for null or a string, depending on what your consumer expects.
  6. Parse again. Paste the result into a formatter or run it through JSON.parse, which, per MDN, throws a SyntaxError if the text is invalid.

If you work in Python, the equivalent check is json.loads(s), which raises JSONDecodeError on invalid input, according to the Python documentation.

Several objects in one file

A frequent surprise: you write several JSON objects to one file in a loop and the result will not load. The Python documentation explains that JSON is not a framed protocol, so repeatedly dumping multiple objects into the same file produces invalid JSON, not a valid multi-document file. Wrap the objects in a single array, or write one object per file.

When the text is not the problem

Sometimes the JSON is fine and the response is not JSON at all. If a request returns an HTML error page, your parser will choke on the first < character and report an unexpected token. Look at the raw response before you edit anything. A server fault, for example, often returns an HTML page; our reference on the 500 Internal Server Error explains the causes. And if the markup in that page looks broken, the notes on unclosed and mismatched HTML tags can help you read it.

A related case is dates. Timestamps inside JSON are just strings or numbers, and the format you pick matters to whoever reads them. Our piece on ISO 8601 and toISOString() covers the surprises there.

Format large or sensitive JSON safely

Formatting is easy for a 2 KB payload. It gets more careful with big files and with data you should not share.

Very large numbers. JavaScript parses JSON numbers into regular floating-point values, so large integers can lose precision before any reviver function runs. MDN's JSON.parse reference recommends transferring such numbers as strings and converting them to BigInt or another arbitrary-precision type when appropriate. If you see an ID that changed its last digits after formatting, this is the likely cause, and the fix belongs in how the data is produced.

Untrusted input. The Python documentation warns that parsing untrusted JSON can use considerable CPU and memory, and recommends limiting the size of data you parse. If your service accepts JSON from the outside, cap the request body size before you parse it.

Format large or sensitive JSON safely

Private data. API responses often contain tokens, emails and internal IDs. Before you paste a payload into any online tool or send it to a colleague, replace secrets with placeholders. If you need to pass a large file along instead of pasting it, a secure file transfer is a better route than a chat window.

Our perspective

We built the formatter because JSON problems rarely arrive at a convenient time. They show up in the middle of a deploy, in a log line, in a webhook that stopped working an hour ago.

Our view is that a formatter should do three things quickly: make the structure readable, tell you plainly where the text breaks, and stay out of your way. That is why the core tools on Pingfloat are designed to work with no installation and no account. You paste, you read, you move on.

We also think formatting is only the first step. Once the syntax is right, the next question is whether the data has the shape your code expects, and that is where schema checks and monitoring come in. A payload can be perfectly valid JSON and still break your integration because a field is missing or has the wrong type.

That is why we keep the JSON tool next to the other things developers reach for in the same debugging session: header inspection, timestamp conversion, regex testing, uptime checks. Fixing a bad payload often leads straight to the next tool, and we would rather you not have to open five different sites to get there.

Andreas

Try it on your own JSON

If you have a payload open right now, paste it into the Pingfloat JSON Formatter. It indents the text, validates it and shows you where it fails, with no installation and no account needed for core use.

Pingfloat

When the JSON comes from your own API, the same suite has what you need around it: the Pingfloat Public API, an uptime monitor for the endpoint serving the data, and a regex tester for the pattern you use to pull values out of logs. You can see the full list of tools on the Pingfloat homepage.

After formatting: check the shape, not just the syntax

Valid syntax says the document can be parsed. It does not say the document is right. A user object with "id": "42" instead of "id": 42 parses fine and may still crash a client that expects a number.

That gap is what JSON Schema is for. It lets you describe required fields and types, then validate payloads against that description at the edge of your system. We walk through two small runnable examples in catching schema bugs at the API boundary, and a step-by-step approach to fixing schema validation errors that starts with syntax, as it should.

If your JSON lives in configuration, you may be weighing it against another format. Our rules for choosing JSON or YAML cover which one suits CI pipelines.

JSON also appears on web pages as structured data. Search engines read it from script tags, and a syntax slip there means the markup is ignored. If you publish structured data markup in JSON-LD, format and validate it like any other JSON first. Then run the page through the Schema Markup Validator, and see our schema markup guide for how to add it.

Habits that prevent most JSON errors

  • Generate JSON with a library, never by string concatenation. JSON.stringify and json.dumps escape quotes and special characters for you.
  • Keep config files strictly JSON. If you want comments, pick a format that allows them instead of adding them to JSON.
  • Send big identifiers as strings. This avoids the precision loss described above.
  • Pick one indentation style per project. Two spaces is the common default in examples, and a consistent style keeps diffs clean.
  • Sort keys when you compare. sort_keys=True in Python makes two versions of a file line up.
  • Validate at the boundary. Parse and check incoming JSON as soon as it enters your system.

FAQ

What is the format of JSON?

JSON is a language-independent text format made of name/value pairs and ordered lists of values. Values can be strings, numbers, true, false, null, objects or arrays, according to json.org. Strings need double quotes, and whitespace between tokens is allowed.

How can I pretty print JSON?

For a one-off, paste it into an online formatter. In JavaScript, call JSON.stringify(value, null, 2). In Python, call json.dumps(obj, indent=2). If you start from a string, parse it first, then stringify or dump it with indentation.

Why do I get "unexpected token" when I parse JSON?

The parser found a character that is not allowed at that spot. Typical causes are trailing commas, single quotes, comments, leading zeros in numbers, or a response that is HTML rather than JSON. Check the position in the error message, then work through the fix table above.

How do I check that my JSON is valid?

Parse it. JSON.parse(text) in a browser or Node throws a SyntaxError for invalid text, and Python's json.loads(s) raises JSONDecodeError. A formatter performs the same parse and shows you the failure location. Parsing confirms syntax only, so use a schema check if you also need the structure to match.

Sources