Why JSON Rejects Leading Zeros and Hexadecimal Numbers

On this page
AI-generated illustration; not taken on location · Comparison of accepted and rejected JSON number spellings with per-component reasons.
AI-generated illustration; not taken on location · A number’s value and its permitted spelling are separate concerns: 012 and 0x10 fail JSON’s grammar even when the intended quantities are obvious.AI-generated illustration

How JSON Defines a Number

JSON rejects 012 because its integer component cannot start with zero and continue with more digits. It rejects 0x10 because hexadecimal notation is not a permitted JSON number form at all. When the intended quantities are twelve and sixteen, the spellings are 12 and 16. When the characters themselves matter, the values become strings: "012" and "0x10".

A number’s value and its permitted spelling are separate concerns. Understanding what a token probably represents does not make its spelling grammatical, and correcting the spelling requires knowing what the field was meant to contain. Syntax first, meaning second — the order matters, because each check answers a different question.

A JSON number has an integer component, optionally preceded by a minus sign, optionally followed by a fractional component and an exponent. Each component has its own rules, so the position of a digit decides the verdict. The integer component permits exactly two shapes:

  • A single 0.
  • A digit from 1 through 9, followed by zero or more digits.

That admits 0, 7, 12, and 120 — in the last, the zero follows a permitted nonzero first digit, so zeros inside an integer were never the problem. The restriction concerns how the integer begins. A fraction is a decimal point followed by at least one digit; 0.12 and 12.0 both pass their respective component rules. The exponent’s digit sequence needs one or more digits with no nonzero-first requirement, which is why 1e02 is valid.

Why 012 Fails While 0 and 0.12 Work

In 012, the integer component begins with zero and continues with additional digits — it fits neither permitted pattern: longer than a single zero, and not beginning with 1–9. An optional minus sign changes nothing: -012 still contains the invalid integer component 012, while -0 is a permitted minus sign before the valid single-zero component.

Token Valid JSON number? Explanation
012 No A zero cannot begin a multi-digit integer component
-012 No The minus sign leaves the invalid integer unchanged
0 Yes The integer is a single zero
-0 Yes Minus sign before a single zero
12 Yes Integer begins with 1–9
120 Yes Zeros after the first nonzero digit are fine
0.12 Yes Integer 0 followed by a permitted fraction
0.012 Yes Fractional digits may begin with zero
1e02 Yes Exponent digits may begin with zero

Even when the surrounding programming language accepts additional numeric forms, the text produced as JSON must follow JSON’s grammar — inspect the emitted text separately from the code that constructed the value. Portability is a documented JSON design goal: a shared grammar gives producers and consumers a common set of permitted forms, and conforming output is a clearer compatibility basis than what one particular implementation happens to accept.

Which Component Contains the Zero?

In 0.012, the digits 012 sit after the decimal point — they belong to the fraction, whose only requirement is a decimal point followed by at least one digit. The integer component remains the single permitted zero. In 1e02, the integer is 1 and 02 is the exponent’s sequence, which carries no nonzero-first restriction.

Identify the component before changing any characters when diagnosing an error. A document-wide instruction to strip zeros would damage both valid numeric positions — fractions and exponents — and strings whose characters must remain intact:

// component-aware check:
const num = '0.012';
const [int, frac] = num.split('.');
int;   // '0' — single zero, permitted
frac;  // '012' — fraction, zeros allowed anywhere
// stripping zeros document-wide would turn 0.012 into .12 — a different value

Representing a Hexadecimal Value in Decimal

JSON’s number grammar contains no hexadecimal form, so the unquoted token 0x10 is invalid wherever a JSON number is required. Recognizing that notation from another context does not make it a permitted spelling here.

When the intended input is hexadecimal 10, compute its value — 1 × 16 + 0 = sixteen — and write the established quantity as a decimal JSON number:

{"value":16}

The conversion changes the notation while retaining the numeric value, and it should be made after confirming how the input was meant to be interpreted — a rejected token alone is not a description of the field’s purpose. When the requirement is preserving the original spelling, use a string instead:

{"notation":"0x10"}
Intended requirement Suitable JSON
Supply the numeric quantity sixteen {"value":16}
Retain the written notation 0x10 {"notation":"0x10"}

Ask whether the receiving application needs a quantity for its work or the original text for display, storage, or comparison. If it needs both, establish separate fields and their meanings before producing the document. Both spellings above are valid, but they preserve different things — the numeric field preserves the quantity, the string field preserves the characters. Syntax validation confirms form; intended use chooses between them.

// both conversions, made explicit:
parseInt('0x10', 16);      // 16 — the established quantity
'0x10';                    // the preserved characters
// choosing without asking what the field means is the error

Preserving Identifiers with Leading Zeros

A digit sequence may identify something rather than express a quantity. If the exact characters matter, changing 012 to 12 discards the leading zero and the original three-character spelling. Compare these valid documents:

{"quantity":12}
{"identifier":"012"}

The first supplies a number; the second supplies a string that retains the identifier’s characters. Choosing quotation marks therefore establishes a data type as well as resolving the invalid unquoted spelling.

Check the field’s documentation, the producer code, and the consumer’s expectations before editing the rejected token:

  • Is the field used as a quantity or as a label that selects a record?
  • Does the consumer require an exact character sequence?
  • Is padding or a fixed character count part of the agreed format?
  • Must "012" and "12" remain distinguishable?

A field name guides the investigation but cannot establish the complete agreement by itself — a name suggesting an identifier should prompt a character-preservation check rather than an automatic conversion. And once the original spelling has been replaced by the number 12, that number alone cannot tell you whether the input was 12, 012, or some other padded spelling; reconstructing a particular identifier needs an additional formatting rule that may not exist anymore. When the original characters are required, preserve them as a string while they are still available.

Runnable Checks and Expected Results

Copy these documents into the parser or inspector you are evaluating. Each row gives a complete input and its expected status under the JSON grammar — these expectations describe syntax validity and intended content, not implementation-specific error messages or serialization formatting:

Input document Expected grammar result
{"n":012} Invalid — integer component has a leading zero followed by digits
{"n":-012} Invalid — the minus sign does not correct the integer component
{"n":0x10} Invalid — hexadecimal numeric notation is unsupported
{"n":12} Valid — the field contains the number twelve
{"n":16} Valid — the field contains the number sixteen
{"id":"012"} Valid — a string preserving 012
{"notation":"0x10"} Valid — a string preserving 0x10
{"n":0.012} Valid — the zero inside the fraction is permitted
{"n":1e02} Valid — exponent digits may start with zero

For a producer correction, record the expected field content before checking its output. If the requirement is an identifier with the characters 012, then {"id":12} fails that requirement even though its number spelling is valid; if the requirement is the quantity sixteen, preserving "0x10" as a string selects a representation that needs its own agreement.

The examples place fields inside objects deliberately: an older JSON grammar restricted a complete JSON text to an object or array, while the newer grammar defines a complete text as any serialized value. Object examples keep that historical difference separate from the numeric spelling under examination. And if a tool accepts either invalid numeric example, check whether it permits extensions — acceptance alone does not establish conformance:

// what a strict parser does with the invalid rows:
JSON.parse('{"n":012}');  // SyntaxError — the grammar, enforced
JSON.parse('{"n":0x10}'); // SyntaxError — same grammar, other clause
// a tool that "accepts" these is offering an extension, not conformance

Correct the Producer Using the Intended Data Type

Trace the rejected token to the code that produces the JSON. Select the intended value and data type where the field’s meaning is known, then serialize that value into conforming text. Correcting a sample helps explain the issue; correcting the producer addresses all subsequent output. The sequence:

  1. Locate the field containing the invalid token and identify where its content originates.
  2. Establish whether the receiving application expects a quantity, an identifier, or preserved notation.
  3. Choose the corresponding value: the number 12, the number 16, the string "012", or the string "0x10".
  4. Serialize the chosen data and inspect the resulting JSON against the grammar.
  5. Check that the receiving application gets the required quantity or exact characters.

For an identifier, the intended result could be {"identifier":"012"}; for an established hexadecimal quantity of sixteen, {"value":16}. These are language-neutral output examples — use the appropriate serialization mechanism in the producer’s environment after making the type decision:

// the producer-side fix, type decided first:
const field = { kind: 'identifier', chars: '012' };
const doc = field.kind === 'quantity'
  ? { n: parseInt(field.chars, 10) }
  : { identifier: field.chars };
JSON.stringify(doc); // '{"identifier":"012"}' — conforming and faithful

Check for Permissive Acceptance

The older specification permits parsers to accept non-JSON forms as extensions, and it requires generators’ output to conform strictly to the grammar. A permissive consumer can therefore accept a spelling that leaves the producer emitting invalid JSON — which conceals a portability problem until another consumer receives the same text and rejects it.

// the trap, in one line:
eval('012'); // 10 in some engines (octal!), 12 in others
// permissive acceptance + ambiguous spelling = value that changes by consumer

That evaluation is the practical argument for strictness: a spelling that only some consumers accept may not even mean the same value everywhere it is accepted. Keep the producer strict and the portability question disappears before it is asked.

Keep Repairs Specific to the Field

Broad text replacement can change unrelated string content. Replacing every occurrence of 012 with 12 could alter a valid identifier string elsewhere in the document; replacing 0x10 with 16 throughout could rewrite text that was intended to preserve notation. Apply the correction where the field’s purpose is available, then verify the emitted syntax and the resulting data together — that makes the repair reviewable and gives future output an explicit representation to follow.

// field-scoped repair, not find-and-replace:
const fix = (doc) => ({
  ...doc,
  n: doc.n === '012-padded-quantity' ? 12 : doc.n // decided per field meaning
});
// the inspector on this site shows each field's type as you review,
// so the two review questions — syntax, purpose — stay answerable together

The whole article compresses to two rules worth keeping together: the grammar decides the spelling, and the field’s meaning decides the type. A rejected 012 is the grammar doing its job; the choice between 12 and "012" belongs to whoever can say what the field is for. Run the nine-row fixture table through the JSON Inspector on this site — it runs locally, flags every leading-zero and hexadecimal token, and turns both rules into visible checks in one paste.

Leave a Reply

Your email address will not be published. Required fields are marked *