1

I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:

SyntaxError: identifier starts immediately after numeric literal

var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};

//works fine
window.alert(stats.COUNTS.TOTAL);

//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);

Here's a fiddle.

How can I access the properties that begin with a number without rewriting the PHP that generated it?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • This has nothing to do with JSON, really. It's just the way Javascript objects work, whether initialized from a literal (which is basically the definition of JSON) or not. `foo.bar` is just a shortcut for `foo["bar"]` that works when the key string happens to make a valid Javascript identifier. – Mark Reed Aug 25 '14 at 22:05
  • 1
    @MarkReed While it is correct that the OP is not accessing a JSON object, if the JSON did not have a property starting with a number, the problem wouldn't exist :p – Ruan Mendes Aug 25 '14 at 22:08

1 Answers1

2

You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *

window.alert(stats.LOAD_AVG["1_MIN"]);

You can use bracket access anywhere really

window.alert(stats["COUNTS"]["TOTAL"]);
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217