0

Possible Duplicate:
How to access a numeric property?

I write a page to access a api from other website. it passes a json in the format of

{
    "a": {
        "2013-01-03": 3965,
        "total": 52284,
        "2013-01-05": 2636,
        "2013-01-04": 4086
    },
    "b": {
        "2013-01-03": 1969,
        "total": 25594,
        "2013-01-05": 1852,
        "2013-01-04": 2031
    },
    "c": {
        "2013-01-03": 6,
        "total": 443,
        "2013-01-05": 13,
        "2013-01-04": 19
    }
}

in my page, i try to access, for example data.a.total it will return 52284, but i cannot access data.a.2013-01-03, it will create an error. It seems that numbers cannot be the key for json. Can someone tell me whats the solution? thanks

Community
  • 1
  • 1
Mr Bohr
  • 125
  • 3
  • 8

2 Answers2

2

You can read it as a['2012-12-13'] using the [] notation for accessing named properties.

For ex:

var data = {"a": {"2013-01-03": 3965, "total": 52284, "2013-01-05": 2636, "2013-01-04": 4086}, "b": {"2013-01-03": 1969, "total": 25594, "2013-01-05": 1852, "2013-01-04": 2031}, "c": {"2013-01-03": 6, "total": 443, "2013-01-05": 13, "2013-01-04": 19}};

data.a['2013-01-03'] will give you 3965

techfoobar
  • 65,616
  • 14
  • 114
  • 135
1

Use the square bracket notation if the keys contain characters that are not valid as JavaScript identifiers:

json.a["2013-01-03"] // 3965
Salman A
  • 262,204
  • 82
  • 430
  • 521