0

The following snippet executes in IE 10 JS console and in Chromes JS console. fiddle

 alert({123:"ABC"}[123]);

However when run this through a linter (for example jslint.com) it complains.

When I read the documentation in json.org I understand the following enter image description here

to mean that it is incorrect to use numbers as names in a JSON object. So does this mean that at least the V8 and Chakra engine are incorrect? Or does this have something to do with strict mode(if it does, it doesn't seem to have any effect when i test it in node)?

Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66

3 Answers3

3

You're confusing Javascript literal syntax with JSON syntax. JSON is a restricted subset of Javascript literal syntax.

The specification of ECMAScript object initialisers can be found here. It contains the following production:

PropertyName :
    IdentifierName
    StringLiteral
    NumericLiteral

So a number is allowed as a property name.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! I just found this question: http://stackoverflow.com/questions/8294088/javascript-object-vs-json which also explains it. – Daniel Figueroa Apr 14 '15 at 10:35
0

The following would be correct:

var jsonString = {"123":"ABC"};
alert(jsonString[123]);

You have to add quotes.

You can find the documentation here http://www.json.org/

Bram
  • 2,515
  • 6
  • 36
  • 58
0

you can use numeric names as strings, e.g. {"123":"ABC"} is a valid JSON while {123:"ABC"} is a valid Javascript expression

Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29