1

I am not exactly sure of the interpretation of the graphic used by json.org to illustrate number syntax in the JSON format, but according to my reading a number cannot begin with a zero.

enter image description here

The way I read it, it is OR a minus sign, then OR a single zero or number beginning with a non-zero digit. In other words:

   0  OK
  -0  OK
   2  OK
  -2  OK
 103  OK
-103  OK
-045  INVALID
 045  INVALID

Is this the correct interpretation?

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • You are right, given the graph, after the initial zero you can only continue with a dot or skip to the exponent part – The Javatar Sep 21 '17 at 13:59
  • Sounds about right. –  Sep 21 '17 at 14:00
  • If it doesn't support hexadecimal, why should it support octal? (`-045` has the value `-37` by the way.) – Raymond Chen Sep 21 '17 at 14:00
  • Possible duplicate of [SyntaxError: Unexpected number](https://stackoverflow.com/questions/21012565/syntaxerror-unexpected-number) – Raymond Chen Sep 21 '17 at 14:07
  • 2
    Possible duplicate of [Why is JSON invalid if an integer begins with 0](https://stackoverflow.com/questions/27361565/why-is-json-invalid-if-an-integer-begins-with-0) – Mark Sep 21 '17 at 14:07

1 Answers1

1

Correct, you cannot have a leading zero on a number in JSON.

The reasons are largely historical: JSON is derived from JavaScript literal notation. At one point, in JavaScript numeric literal notation, a leading 0 meant octal (base 8), so 010 would be the number eight. This was in the 1st and 2nd editions of the ECMAScript spec (1997 and 1998, respectively). In the 3rd edition it was deprecated to an optional "additional" syntax, and in the 5th edition (there was no 4th edition) it was forbidden in the new "strict" mode. Finally ES2015 (also called the 6th edition, it's where TC39 decided to start using years) introduced an unambiguous Octal notation: A leading 0o prefix (case-insensitive), analogous to the 0x prefix for hex.

During all this curfluffle about whether a leading 0 should mean octal, Crockford was defining JSON, and not allowing the leading 0 simplifies things and avoids confusion, both of which were important when JSON was defined. He even decided not to support hex, for the sake of simplicity/ease of parsing.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875