Common JSON Formatting Errors and How to Fix Them: A Practical Developer Guide
JavaScript Object Notation (JSON) is the undisputed standard for data interchange across web APIs, microservices, mobile apps, and cloud configurations. Despite its ubiquity and conceptual simplicity, JSON is notoriously strict. Unlike flexible JavaScript object literals, the official JSON specification (IETF RFC 8259) permits zero stylistic leniency.
A single misplaced comma or unescaped quotation mark will cause standard JSON parsers (JSON.parse()) to crash with unhelpful error messages like SyntaxError: Unexpected token in JSON at position 142.
In this guide, we break down the seven most frequent JSON formatting mistakes, explain the underlying specification rules, and provide actionable solutions for writing bulletproof payloads.
1. Trailing Commas in Arrays and Objects
Trailing commas (commas placed after the final element in an array or object) are standard practice in modern JavaScript, TypeScript, Python, and Go because they produce cleaner version-control diffs:
/* INVALID JSON: Trailing comma on line 4 */
{
"name": "Production Database",
"port": 5432,
"ssl": true,
}
Why It Fails:
Under RFC 8259, commas are strictly defined as separators between elements, not terminators. If a comma appears after the final item, the parser expects another element to follow. Finding a closing brace } instead triggers an immediate syntax error.
The Fix:
Always remove the comma after the final key-value pair or array entry:
/* VALID JSON */
{
"name": "Production Database",
"port": 5432,
"ssl": true
}
2. Single Quotes Instead of Double Quotes
In JavaScript and Python, single quotes (') and double quotes (") are largely interchangeable for string definition. In JSON, however, single quotes are illegal:
/* INVALID JSON: Single quotes used */
{
'status': 'active',
'errorCode': 404
}
Why It Fails:
The JSON grammar explicitly defines a string as a sequence of Unicode characters enclosed in double quotation marks ("). Single quotes have no syntactic meaning in standard JSON.
The Fix:
Replace all single quotation marks surrounding keys and string values with double quotes:
/* VALID JSON */
{
"status": "active",
"errorCode": 404
}
3. Unquoted Object Keys
Developers accustomed to writing JavaScript object literals frequently omit quotation marks around property names:
/* INVALID JSON: Keys are not quoted */
{
host: "api.internal.service",
timeout: 3000
}
Why It Fails:
JavaScript object keys can be unquoted identifiers as long as they follow variable naming conventions. In JSON, every object key must be a valid JSON string enclosed in double quotes.
4. Comments in Standard JSON
Configuration files written in JSON (such as .eslintrc or tsconfig.json) often require explanatory annotations. However, standard RFC 8259 JSON does not permit comments of any kind:
/* INVALID JSON: Comments are not supported */
{
// Primary connection pool
"maxConnections": 20,
/* Timeout in milliseconds */
"idleTimeout": 10000
}
Why It Fails:
Douglas Crockford, the creator of JSON, intentionally excluded comments from the specification to prevent developers from adding parsing directives that would splinter cross-language interoperability.
The Fix:
- If working with standard JSON APIs: Strip all comments before transmission or serialization.
- If configuring developer tools: Use formats designed to accept comments, such as JSONC (JSON with Comments, used by VS Code) or JSON5.
5. Floating-Point Precision Loss with 64-bit Integers
A subtle but dangerous issue in JSON processing involves large integer values, such as 64-bit database primary keys (Snowflake IDs or Twitter/X tweet IDs):
{
"userId": 18446744073709551615
}
Why It Fails:
While the JSON specification technically supports arbitrary-precision numbers, virtually every web browser and Node.js runtime parses JSON numbers into IEEE 754 double-precision floating-point numbers (float64).
In IEEE 754, the maximum safe integer is $2^{53} - 1$ (Number.MAX_SAFE_INTEGER, or 9,007,199,254,740,991). Any integer exceeding this threshold will suffer silent truncation during JSON.parse():
const payload = '{"userId": 9007199254740993}';
console.log(JSON.parse(payload).userId);
// Output: 9007199254740992 <-- Silent bit corruption!
The Fix:
Always serialize 64-bit integers and high-precision IDs as strings in JSON payloads:
{
"userId": "18446744073709551615"
}
6. Unescaped Backslashes in Paths and Regexes
Windows file paths and regular expression patterns frequently contain backslashes (\):
/* INVALID JSON: Unescaped backslashes */
{
"uploadDirectory": "C:\Users\Admin\Documents",
"pattern": "^\d{3}-\d{2}-\d{4}$"
}
Why It Fails:
In JSON, the backslash character is reserved as an escape prefix (e.g., \", \\, \/, \b, \f, \n, \r, \t, \uXXXX). When the parser encounters \U in C:\Users, it expects a four-character hexadecimal Unicode sequence. Because 's' is not a valid hex digit, the parser throws an invalid escape sequence error.
The Fix:
Double-escape all backslashes by prepending another backslash (\\):
/* VALID JSON */
{
"uploadDirectory": "C:\\Users\\Admin\\Documents",
"pattern": "^\\d{3}-\\d{2}-\\d{4}$"
}
7. Circular References During Serialization
When attempting to serialize complex application state or interconnected data structures into JSON using JSON.stringify(), developers frequently encounter:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'parent' -> object with constructor 'Object'
--- property 'child' closes the circle
Why It Fails:
JSON represents a hierarchical tree structure. If an object references another object that in turn points back to the first object, a naive traversal creates an infinite recursive loop.
The Fix:
Use a custom replacer function or a cycle-breaking utility (such as flatted or WeakSet tracking) to eliminate cyclical references prior to serialization:
function getCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
return value;
};
}
const safeJson = JSON.stringify(complexObj, getCircularReplacer(), 2);
Format and Validate JSON Safely Online
Diagnosing syntax errors manually inside huge, minified JSON payloads is exhausting. You can use Stringra’s Free JSON Formatter & Validator to instantly identify syntax errors, inspect line numbers, and beautify your payloads.
Because Stringra runs 100% client-side in your browser, your sensitive configurations, database records, and API responses are never uploaded to any remote server.