DEV Community

Owais Khan
Owais Khan

Posted on Originally published at owaiskhan.website

Invalid JSON Format Examples: Rules, Common Errors, and Syntax Fixes

An invalid JSON format is any text payload that breaches standard JSON structural rules, such as using single quotes, omitting double quotes on keys, leaving trailing commas, or including arithmetic expressions and currency symbols in numeric fields. When a parser encounters these violations, data interchange halts immediately with a syntax or parsing exception.

Syntax Violation Reference for Invalid JSON Formats

JSON syntax requires rigid adherence to structural primitives. The following reference table outlines common invalid patterns, concrete non-compliant examples, the parsing failure triggered, and the structural rule mandated by the standard.

Category Invalid Example Syntax Rule Breached Standard Requirement
String Quoting 'device_id' Single quotes used instead of double quotes All strings must be wrapped in double quotes.
String Escaping "User said "Active" now" Unescaped inner quotation marks Quotation marks within a string must use the backslash escape sequence (\").
Key Representation { status: "pending" } Unquoted object property name Keys within an object must be strings enclosed in double quotes.
Key-Value Separator { "sku" "A-102" } Missing colon between key and value A colon (:) must separate every key from its assigned value.
Missing Value { "sku": } Missing value after colon Every key-value pair must contain a complete value after the separator.
Object Missing Key { { "nested": true } } Object structure lacking an identifying member key Object members must consist of a key-value pair, not a bare value.
Array Trailing Comma [ "item_1", "item_2", ] Extra comma after final element Comma separates elements; no comma may follow the final element.
Array Intermediate Comma [ "item_1",, "item_2" ] Consecutive commas without an element Commas must strictly separate populated values.
Array Structure Mismatch [ "alpha", "beta" } Array closed with a curly brace Arrays open with [ and must close with square bracket ].
Array Pair Mismatch [ "sensor_1", "reading": 42 ] Key-value pair inserted directly into an array Arrays hold values only; key-value pairs belong only inside objects.
Numeric Currency { "total": £45.00 } Currency symbol prefixed to number Numbers must not contain currency signs or alphabetical symbols.
Numeric Expression { "total": 100 * 0.05 } Mathematical equation used as a value JSON values cannot contain mathematical expressions; only evaluated literals.
Numeric Leading Zero { "counter": 07 } Number contains an invalid leading zero Numbers in floating-point format cannot contain extraneous leading zeroes.
Literal Casing { "active": True, "payload": NULL } Capitalized boolean and null literals Booleans and null values must use lowercase literals: true, false, null.
Trailing Comma in Object { "id": 10, "flag": false, } Extra comma after final key-value pair The final member of an object must not be followed by a comma.

Deriving Structural Rules: Why These Formats Fail Parser Evaluation

JSON (JavaScript Object Notation) operates as a strict data-interchange format derived from JavaScript object literal syntax, yet it does not permit JavaScript's syntactic flexibility. Parsers analyze tokens sequentially, and any divergence from the specification causes the parser to fail.

String and Key Formatting

JSON specifies that every sequence of Unicode characters intended as a string must be bounded by standard double quotes. When an author attempts to use single quotes (such as 'inventory'), the lexical analyzer fails to recognize the token as a JSON string. Furthermore, whenever double quotes occur naturally inside a string payload, they must be escaped using a backslash (\"). Unescaped double quotes terminate the token prematurely, leaving trailing characters that trigger parser errors.

Keys within object members are subjected to the same double-quoting rule. While JavaScript object literals permit unquoted keys when names avoid reserved keywords, JSON strictly forbids unquoted keys. A parser seeing { item_count: 5 } halts because an unquoted token in the key position is not a valid JSON string.

Object and Array Delimiters

Objects are encapsulated strictly within curly brackets ({}), and arrays are encapsulated within square brackets ([]). An empty object is represented as {}, and an empty array is represented as []. Every member within an object or element within an array must be followed by a comma to delineate boundaries—except for the final member or element.

Trailing commas represent one of the most frequent syntax errors in data pipelines. A comma indicates to the parser that another token follows. If the parser hits a closing delimiter directly after a comma (for example, ["alpha", "beta", ] or {"code": 200, }), it expects a valid string, number, boolean, null, object, or array token. Because it encounters the closing bracket instead, it reports a missing element or an unexpected token.

Similarly, arrays can hold only sequential values. Attempting to place an object member—such as "metric": 88—directly inside an array without wrapping curly brackets violates the array grammar.

Numeric Values, Booleans, and Null

JSON numbers are represented in double-precision floating-point format. They must consist purely of digits, an optional negative sign, an optional decimal point, and an optional exponent. Currency symbols (such as $, €, or £) and arithmetic operations (such as 50 + 20) are not numeric tokens. Parsers do not evaluate mathematical statements or strip unit symbols.

Boolean values are limited to the two exact lowercase literals true and false. The null state must be written as the lowercase literal null. Using uppercase or capitalized variants—such as True, FALSE, or Null—causes a parser to interpret them as unquoted identifiers, leading to an immediate syntax rejection.

Complex data structures such as dates are not native JSON data types. Dates cannot be represented as bare timestamp objects and must instead be converted into strings.

Resolving Multi-Error Payloads and Structural Delimiter Mismatches

Real-world invalid JSON payloads often contain multiple compounded syntax errors. Reviewing a broken payload line by line allows each syntax failure to be isolated and corrected.

Unparsed Broken Payload Example

{
 'transaction_id': 9481,
 "store": "Main Street "Flagship" Store",
 "tax_rate": 0.0825,
 "subtotal": $120.00,
 "discount": 120.00 * 0.10,
 status: "completed",
 "verified": True,
 "items": [
 "unit_a",
 "unit_b",
 ],
 "metadata": {
 "device": "POS_01",
 "backup": 
 }
 "note": null,
}
Enter fullscreen mode Exit fullscreen mode

Diagnostic Walkthrough

  1. Line 2: 'transaction_id': 9481, — The key is enclosed in single quotes. All keys must be enclosed in standard double quotes: "transaction_id".
  2. Line 3: "store": "Main Street "Flagship" Store", — Double quotes inside the string value are unescaped. The inner quotes must be escaped with backslashes: "Main Street \"Flagship\" Store".
  3. Line 5: "subtotal": $120.00, — The number contains a currency symbol ($). JSON numbers cannot include currency signs. The value must be formatted as raw digits: 120.00.
  4. Line 6: "discount": 120.00 * 0.10, — An arithmetic expression is written in place of a value. The calculation must be evaluated beforehand and passed as a single numeric literal: 12.00.
  5. Line 7: status: "completed", — The key lacks enclosing double quotes. It must be written as "status".
  6. Line 8: "verified": True, — The boolean literal uses a capital letter. The valid JSON representation requires lowercase: true.
  7. Line 11: "unit_b", — The array element has a trailing comma immediately preceding the closing square bracket. The comma must be removed.
  8. Line 15: "backup": — The key-value pair in the nested object has a key and colon but no assigned value. It must either receive a valid JSON value (such as null) or be removed.
  9. Line 16: } — The nested object closes, but the author omitted the separating comma required before the subsequent key-value pair ("note"). A comma must follow }.
  10. Line 17: "note": null, — A trailing comma appears after the final member of the outer object before the closing curly brace. The comma must be removed.

Corrected Valid JSON Payload

Applying these corrections transforms the unparseable payload into a standard-compliant JSON text string:

{
 "transaction_id": 9481,
 "store": "Main Street \"Flagship\" Store",
 "tax_rate": 0.0825,
 "subtotal": 120.00,
 "discount": 12.00,
 "status": "completed",
 "verified": true,
 "items": [
 "unit_a",
 "unit_b"
 ],
 "metadata": {
 "device": "POS_01",
 "backup": null
 },
 "note": null
}
Enter fullscreen mode Exit fullscreen mode

When verifying complex multi-line structures, using an automated JSON Formatter eliminates the manual overhead of tracing nested brackets, balancing quotes, and pruning invalid trailing commas.

Parser Variations, Relaxed Specifications, and Edge Scenarios

Although the JSON standard is unambiguous, software environments handle edge scenarios and malformed inputs with varying levels of tolerance.

The Single Root Value Rule and Multiple Objects

A JSON text string must contain exactly one top-level JSON value. This value is typically an object ({}) or an array ([]), though single scalar values (such as an isolated string or number) are syntactically valid JSON text strings. A common source of invalid JSON occurs when concatenating multiple JSON objects consecutively without an enclosing array or delimiter, such as:

{ "record": 1 }
{ "record": 2 }
Enter fullscreen mode Exit fullscreen mode

Standard JSON parsers parse the first object, encounter the opening brace of the second object where an end-of-file is expected, and immediately throw a syntax error. To make this valid JSON, both objects must be contained within a single array: [{ "record": 1 }, { "record": 2 }].

Standard Parsers vs. Permissive Deserializers

Strict JSON parsers—such as Python's json.loads() or JavaScript's native JSON.parse()—strictly reject any deviations. In JavaScript, error handling requires encapsulating calls within try {... } catch (error) {... } blocks to capture parsing failures gracefully. In PHP, functions like json_decode() will reject payloads that lack double-quoted keys or contain trailing commas.

In contrast, certain modern deserialization frameworks and libraries provide configuration settings to allow relaxed parsing. For example, some deserializers permit options to tolerate trailing commas, decode numbers wrapped in string quotes, or allow code comments. However, payloads utilizing these relaxed extensions are technically invalid JSON and will fail when transmitted to external endpoints adhering to the standard application/json MIME type.

Top comments (0)