Most "my API is broken" moments I have seen turn out to be one stray character in a JSON body. The server is fine, the client is fine, and a single comma has been quietly breaking the parse for an hour.
This guide covers what valid JSON actually is, the five mistakes that cause most parse errors (with the real error messages you will see), and three ways to format, minify and validate JSON without installing anything new. Every code sample below was run before I pasted it here (Node 24, Python 3, jq).
What counts as valid JSON
JSON is stricter than a JavaScript object literal. The rules fit in a short list:
- Keys are always strings in double quotes.
- Strings use double quotes only.
- Values are a string, number, object, array,
true,falseornull. -
No trailing commas, no comments, no
undefined, noNaN. - Numbers cannot have leading zeros (
01is invalid). - Control characters such as a raw newline cannot appear inside a string; they must be escaped as
\n.
The formal definitions are RFC 8259 and ECMA-404. If a payload follows these rules, every compliant parser will accept it.
The five errors behind most parse failures
I ran each of these through JSON.parse in Node 24. The wording of the message differs between engines and versions, but the cause is always the same.
for (const bad of [
'{"a": 1,}',
"{'a': 1}",
'{id: 101}',
'{"a": "line1\nline2"}',
'{"a": 01}',
]) {
try {
JSON.parse(bad);
} catch (e) {
console.log(JSON.stringify(bad), '->', e.message);
}
}
Output:
"{\"a\": 1,}" -> Expected double-quoted property name in JSON at position 8 (line 1 column 9)
"{'a': 1}" -> Expected property name or '}' in JSON at position 1 (line 1 column 2)
"{id: 101}" -> Expected property name or '}' in JSON at position 1 (line 1 column 2)
"{\"a\": \"line1\nline2\"}" -> Bad control character in string literal in JSON at position 12 (line 1 column 13)
"{\"a\": 01}" -> Unexpected number in JSON at position 7 (line 1 column 8)
Here is how to read them:
-
Trailing comma (
{"a": 1,}). Valid in modern JavaScript, illegal in JSON. The parser reaches the}while still expecting another key. Remove the last comma. -
Single quotes (
{'a': 1}). Strings and keys must use double quotes. This one usually comes from pasting a Pythonrepr()or a JavaScript object into a request body. -
Unquoted keys (
{id: 101}). Same fix:{"id": 101}. -
Raw newline inside a string. Multi-line text needs
\n. This is common when a log line or a textarea value is dropped straight into a JSON template. -
Leading zeros (
01). Send it as a string ("01") if the leading zero matters, for example a postcode or an ID, or as1if it does not.
Notice that every message includes a position. When the payload is a single 40 KB line, "position 8" is useful, but "position 31,407" is not. That is the point where I stop reading raw text and format it.
Format and minify: three ways
1. In the browser, with no setup. Paste the payload into a formatter that validates as it formats. I use the JSON Formatter on ToolSphare, which lets you pick 2- or 4-space indentation, minify, and see the exact line and character of a syntax error. The page says the processing happens in your browser rather than on a server, but if the payload contains tokens or customer data, check the privacy claim of any online tool (including mine) before you paste it.
2. In JavaScript. JSON.stringify takes an indentation argument:
const raw = '{"id":101,"name":"Ayesha","tags":["pdf","json"],"active":true,"address":{"city":"Lahore","zip":null}}';
const data = JSON.parse(raw);
console.log(JSON.stringify(data, null, 2)); // pretty, 2 spaces
console.log(JSON.stringify(data)); // minified
The first call prints the object over 13 indented lines; the second returns the compact single-line string again.
3. On the command line. Python ships with a formatter, and jq is worth installing if you read API output regularly:
echo '{"name":"Ayesha","tags":["pdf","json"]}' | python3 -m json.tool
echo '{"name":"Ayesha","tags":["pdf","json"]}' | python3 -m json.tool --compact
echo '{"a":[1,2]}' | jq .
Both tools also validate. Feeding {"a": 1,} to python3 -m json.tool fails with Illegal trailing comma before end of object: line 1 column 8 (char 7).
When to beautify and when to minify
Use the pretty-printed form wherever a human reads the data: code review, config files such as package.json, bug reports and log analysis. Use the minified form wherever a machine reads it and size matters: HTTP responses, cookies, query strings and records in a document database. Minifying only removes whitespace, so the data is identical; the saving depends on how much indentation the original had. Do not hand-edit minified JSON in production. Format it, change it, then minify it again, so a typo cannot hide in a single long line.
One more habit that pays off: keep a small sample payload next to your tests. When a parser complains about real traffic, diffing it against a known-good sample shows the change immediately.
Validate safely in code
Never let a bad payload crash your handler. Wrap the parse and return a result you can log:
function safeParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
return { ok: false, error: err.message };
}
}
console.log(safeParse('{"a": 1}')); // { ok: true, value: { a: 1 } }
console.log(safeParse('{"a": }')); // { ok: false, error: `Unexpected token '}', "{"a": }" is not valid JSON` }
In Python, json.JSONDecodeError carries the details as attributes, so you can point at the problem instead of printing a stack trace:
import json
try:
json.loads('{"a": 1,}')
except json.JSONDecodeError as e:
print(e.msg, e.lineno, e.colno, e.pos)
# Illegal trailing comma before end of object 1 8 7
Remember that "valid JSON" only means "well-formed". It does not mean the data has the fields you expect. For that you need a schema check (JSON Schema, Zod, Pydantic) after the parse succeeds.
What JSON cannot hold
Round-tripping data through JSON.stringify quietly drops or changes some values:
console.log(JSON.stringify({ d: new Date(0), u: undefined, f() {}, n: NaN }));
// {"d":"1970-01-01T00:00:00.000Z","n":null}
-
undefinedand functions are omitted from objects. -
NaNandInfinitybecomenull. - A
Datebecomes an ISO string, and it comes back as a string, not aDate.
If you see a field vanish after a save-and-load cycle, this is usually why.
A short debugging checklist
- Format the payload first. Most errors are obvious once the structure is indented.
- Look at the reported position, then check the characters just before it: a trailing comma, a quote, or an unescaped character.
- Check the quotes: only straight double quotes. Smart quotes from a document or chat app (
“ ”) are invalid, and they are easy to miss. - Confirm the
Content-Typeheader isapplication/jsonand the body is not double-encoded (a JSON string that contains JSON). - Only then look at schema and business logic.
Formatting takes seconds and rules out the most common cause before you spend an hour on the rest of the stack.
If you have a JSON error that none of these explain, paste the error message (not the payload) in the comments and I will take a look.
Disclosure: I build ToolSphare, the free online tools site that hosts the formatter mentioned above.
About the Developer
Muhammad Wasim is a Software Engineer and the founder of ToolSphare. He designs and maintains ToolSphare, which has 718 live tools across 28 categories, free coding courses and a browser code editor. Everyday use needs no forced sign-up.
What he builds for ToolSphare:
- Free online tools for PDF, image, text and utility workflows
- Developer tools such as JWT, QR, color, favicon and coding helpers
- Free coding courses with structured lessons
- An online code editor for Python, C++, C#, Java and HTML/CSS/JavaScript
ToolSphare is a Laravel app built with crawlable HTML, canonical URLs, structured data, XML sitemaps and IndexNow-ready discovery.
- Developer profile: toolsphare.com/developer
- About ToolSphare: toolsphare.com/about
- Contact: contact@toolsphare.com or toolsphare.com/contact
Top comments (0)