How to Format JSON and Fix Common JSON Validation Errors

How to format JSON so it's readable, validate it, and fix the most common JSON errors: trailing commas, single quotes, comments, unescaped characters and more.

By the MakeItFlow team Updated 6 min read
Share LinkedIn X Facebook WhatsApp
How to Format JSON and Fix Common JSON Validation Errors

To format JSON, paste it into a JSON formatter or run it through your language's built-in tools, such as JSON.stringify(data, null, 2) in JavaScript or python -m json.tool. Formatting adds indentation and line breaks. If the formatter reports an error instead, the JSON is invalid, usually because of a trailing comma, single quotes or a missing bracket.

JSON (JavaScript Object Notation) is how most websites, apps and APIs pass data around. It also crops up in config files, structured data for SEO, automation platforms like Zapier and Make, and webhook payloads. It looks simple, but its rules are strict, and one stray comma breaks the whole file.

This guide covers how to format JSON properly, what JSON validation actually checks, and how to fix the errors you're most likely to hit. Make It Flow's free JSON formatter formats, validates and minifies JSON in your browser, and points to the line that's broken.

Key takeaways

  • Formatting (pretty-printing) only changes whitespace; validation checks the JSON follows the strict rules in RFC 8259.
  • Most JSON errors come from writing JavaScript habits into JSON: trailing commas, single quotes, unquoted keys and comments are all invalid.
  • The line and column in a parser error usually point just after the real mistake, so look at the character before it.
  • Never build JSON by gluing strings together; use your language's JSON encoder so quotes and special characters are escaped correctly.

How to format JSON

"Formatting" (also called pretty-printing or beautifying) changes only the whitespace. The data stays exactly the same.

Minified JSON, the kind APIs send to save bytes:

{"business":"Acme Plumbing","open":true,"services":["boilers","bathrooms"],"rating":null}

The same data formatted with 2-space indentation:

{
  "business": "Acme Plumbing",
  "open": true,
  "services": [
    "boilers",
    "bathrooms"
  ],
  "rating": null
}

Ways to format JSON

Method Command or action
Browser tool Paste into our JSON formatter and choose an indent
JavaScript / Node.js JSON.stringify(JSON.parse(text), null, 2)
Python python -m json.tool input.json
Command line (jq) jq . input.json
VS Code Open the file and run "Format Document"
PHP json_encode($data, JSON_PRETTY_PRINT)

Two spaces is the most common indent for JSON, but four spaces or tabs are equally valid. Pick one and keep it consistent in your project.

When to minify instead

For anything sent over the network, minified JSON is smaller. Gzip or Brotli compression narrows the gap a lot, but there's no reason to ship indentation in API responses. Format for humans, minify for machines.

What JSON validation checks

Formatting a document forces a parser to read it, so formatting and validation usually happen together. A JSON validator checks that your text follows the grammar in RFC 8259, the JSON standard. That grammar allows just six kinds of value:

Type Example Rules
Object {"name": "Acme"} Keys must be strings in double quotes
Array [1, 2, 3] Ordered list, comma-separated
String "hello" Double quotes only, special characters escaped
Number 42, -3.5, 1e6 No leading zeros, no NaN or Infinity
Boolean true, false Lowercase only
Null null Lowercase only

That's the whole language. Anything else, including comments, undefined, dates and functions, isn't JSON.

Syntax validation vs schema validation

Syntax validation answers "is this valid JSON?" Schema validation answers "is this the JSON my app expects?" For example, it can check that price is a number and email is present. JSON Schema is the common standard for that second kind of check. A document can be perfectly valid JSON and still be wrong for your API.

JSON vs JavaScript objects

Most JSON errors happen because JSON looks like JavaScript but is much stricter. Code that runs fine as a JavaScript object literal often fails as JSON:

Feature JavaScript object JSON
Unquoted keys {name: "Acme"} Allowed Invalid
Single quotes 'Acme' Allowed Invalid
Trailing comma [1, 2, ] Allowed Invalid
Comments // note Allowed Invalid
undefined Allowed Invalid
NaN, Infinity Allowed Invalid
Functions and dates Allowed Invalid (dates must be strings)
Hex numbers 0xFF Allowed Invalid

JSON.stringify() handles some of these quietly. It drops undefined values and functions from objects, and turns NaN and Infinity into null. That can cause confusing "missing field" bugs later on.

Common JSON validation errors and how to fix them

Parser error messages vary by browser and language. Firefox reports something like JSON.parse: unexpected character at line 1 column 14, while Chrome and Node.js say something like Unexpected token or Expected double-quoted property name, with a position. MDN's JSON.parse error reference lists the Firefox messages.

Tip: the reported position is where the parser gave up. The real mistake is often the character just before it, or the end of the previous line.

1. Trailing commas

{
  "name": "Acme",
  "city": "Leeds",
}

Fix: delete the comma after the last item in every object and array. This is one of the most common JSON errors, especially in hand-edited config files.

2. Single quotes

{ 'name': 'Acme' }

Fix: use double quotes for every key and every string value: { "name": "Acme" }.

3. Unquoted keys

{ name: "Acme" }

Fix: quote the key: { "name": "Acme" }.

4. Comments

{
  // business name
  "name": "Acme"
}

Fix: remove the comment. If you need notes, add a field such as "_comment": "...", or use a format that allows comments (JSONC, JSON5, YAML), provided the tool reading the file supports it.

5. Unescaped characters inside strings

{ "quote": "She said "hello"", "path": "C:\new\folder" }

Double quotes and backslashes inside a string must be escaped, and raw line breaks and tabs aren't allowed:

{ "quote": "She said \"hello\"", "path": "C:\\new\\folder" }

The Windows path example is a nasty one: \n in C:\new is valid JSON, but it means a newline, so the parse succeeds and the data is silently wrong.

6. Missing or extra brackets

An unclosed { or [ often produces an "unexpected end of JSON input" error. Formatting the document makes the nesting visible. Look for the place where the indentation stops making sense.

7. Missing commas between items

{ "a": 1 "b": 2 }

Fix: { "a": 1, "b": 2 }. This often happens when you copy and paste blocks together.

8. Invalid numbers

01, .5, 1., +1, NaN and 0xFF are all invalid. Use 1, 0.5, 1.0, 1 and null (or a string), and convert hex to decimal.

9. "Unexpected token < in JSON at position 0"

This one isn't a JSON problem at all. Your code asked for JSON and received HTML, usually an error page, a login page or a 404. Check the URL, the response status and the Content-Type header. Our HTTP status checker shows what an endpoint actually returns.

10. Invisible characters

A byte order mark (BOM) at the start of a file, or "smart quotes" pasted from Word or a chat app (“ instead of "), make JSON fail with an error that looks impossible. Retype the quotes, or save the file as UTF-8 without a BOM.

JSON error quick reference

Error message (typical) Likely cause
Expected double-quoted property name Trailing comma, single quotes or an unquoted key
Unexpected token } or ] Trailing comma before it
Unexpected end of JSON input Missing closing bracket, or an empty response
Unexpected token < at position 0 HTML returned instead of JSON
Bad control character in string literal A raw newline or tab inside a string
Bad escaped character A lone backslash, such as in a Windows path
Unexpected non-whitespace character after JSON Two JSON documents joined together, or extra text at the end

Avoiding JSON errors in the first place

  1. Never build JSON by string concatenation. '{"name":"' + name + '"}' breaks the moment a name contains a quote. It can also let users inject fields. Use JSON.stringify(), json_encode() or json.dumps().
  2. Validate at the boundary. Parse incoming JSON inside a try/catch and return a clear error rather than crashing.
  3. Use schema validation for APIs, so bad data is rejected with a useful message.
  4. Let your editor help. VS Code and most IDEs highlight JSON syntax errors as you type.
  5. Diff before you deploy. When a config change breaks something, compare the old and new versions in a diff checker. Format both first so the comparison is meaningful.
  6. Converting spreadsheets? Use a converter such as our CSV to JSON tool rather than editing by hand. For XML feeds and API responses, the XML to JSON converter does the same job.

JSON in SEO: structured data

If you run a business website, the JSON you're most likely to touch is JSON-LD structured data, the <script type="application/ld+json"> block that describes your business, products or articles to search engines. The same syntax rules apply, and one trailing comma makes Google ignore the whole block. Check it with our schema markup validator, or build it with the schema generator. Our structured data guide covers which types are worth adding.

More developer utilities are collected on our free tools for web development page.

FAQ

How do I format JSON online?

Paste your JSON into a formatter such as our free JSON formatter, choose an indentation level and format it. A good formatter also validates as it goes, and it highlights the line where parsing failed if the JSON is invalid. Browser-based formatters that run locally avoid sending sensitive data to a server.

Why is my JSON invalid?

The most common causes are a trailing comma after the last item, single quotes instead of double quotes, unquoted keys, comments, unescaped quotes or backslashes inside strings, and missing brackets. JSON is far stricter than JavaScript, so text that works as a JavaScript object often fails as JSON.

Are trailing commas allowed in JSON?

No. RFC 8259 doesn't allow a comma after the last element of an object or array, and standard parsers such as JSON.parse() reject it. JavaScript, JSON5 and some config formats allow trailing commas, which is why they slip into JSON so often. Remove them before parsing.

Can JSON have comments?

Standard JSON can't. Comments cause a syntax error in JSON.parse() and most other strict parsers. Some tools accept variants such as JSONC (used by VS Code settings) or JSON5, which do allow comments. If a file must be strict JSON, store notes in a dedicated field such as "_comment" instead.

What's the difference between JSON and a JavaScript object?

JSON is a text format for exchanging data, while a JavaScript object is a live structure in memory. JSON requires double-quoted keys and strings, and it allows only strings, numbers, booleans, null, arrays and objects. JavaScript objects can hold functions, undefined and dates, and they allow single quotes and trailing commas.

What does "Unexpected token < in JSON at position 0" mean?

It means your code tried to parse an HTML page as JSON. The < is the start of a tag such as <!DOCTYPE html>. The server probably returned an error page, a redirect to a login screen, or a 404. Check the request URL, the HTTP status code and the response body.

#json #json validation #web development #apis

More guides for your industry

Free checklist (PDF)

Free web developers website checklist

31 practical checks for web developers: website speed and mobile, Google Business Profile and reviews, email security, booking and enquiry handling, and AI search visibility. Each one says why it matters, and many link to a free tool that checks it.

We email you the PDF and nothing else unless you tick the box. See the privacy policy.

Written by the MakeItFlow team

We build the website audit these guides are based on. Every fact is checked against the primary sources listed above and this guide was last reviewed on 30 October 2026 . How we research and check

Share LinkedIn X Facebook WhatsApp

Check your own site in 30 seconds

Run a free audit covering speed, SEO, DNS, email authentication and security headers — and get a prioritised fix list.

Weekly newsletter

One practical website fix, every week

New guides on speed, SEO, email deliverability and security — straight to your inbox. No spam, unsubscribe in one click.

Keep reading