Martin Burch
Martin Burch

Reputation: 2911

Are decimals without leading zeros valid JSON?

Given the JSON document

{"percentageAmount": .01}

Running it by JSONLint.com results in the error:

Parse error on line 2:
..."percentageAmount": .01}
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

On the other hand, this is valid:

{"percentageAmount": 0.01}

The code is parsed correctly if assigned to a variable as a JavaScript literal, but of course there are many things that are OK for JavaScript variables that aren't JSON spec.

Why is this against JSON spec?

Upvotes: 14

Views: 4230

Answers (2)

maerics
maerics

Reputation: 156434

Nope.

According to the railroad diagram for numbers at JSON.org, numbers with fractional values must have digits before the decimal point:

Diagram showing that numbers with fraction parts must have a digit before the decimal point.

Upvotes: 14

Quentin
Quentin

Reputation: 943586

Are decimals without leading zeros valid JSON?

From the specification:

  number = [ minus ] int [ frac ] [ exp ]

  decimal-point = %x2E       ; .

  digit1-9 = %x31-39         ; 1-9

  e = %x65 / %x45            ; e E

  exp = e [ minus / plus ] 1*DIGIT

  frac = decimal-point 1*DIGIT

  int = zero / ( digit1-9 *DIGIT )

  minus = %x2D               ; -

  plus = %x2B                ; +

  zero = %x30                ; 0

The only part of a number that is mandatory is int which is defined as zero or 1-9 followed by any number of digits.

So JSON Lint is correct.

Why is this against JSON spec?

As far as I know, the author's reasons for defining it that way are not documented anywhere.

Upvotes: 9

Related Questions