Possible Duplicate:
How to access a numeric property?
I am trying to read an object where the keys are numbers. But unfortunately, when I try reading this object:
Salary:{
"2012_08":"5555",
"2012_09":"6666",
"2012_10":"7777"
}
var augsalary = salary.2012_08;
it throws an error. My question is this: “2012_08” is the year month combination and that cannot change to be stored as a string. How can I still access the value with that key?
First, your Javascript code is invalid, perhaps you meant
Second, an all too common confusion is to talk of JSON objects.
Salaryis NOT a JSON object, it is a JavaScript object. JSON is a notation forexpressing a large subset of all JavaScript objects as strings. These strings can then
be transmitted to other parts of your code or other computers where they can be converted back into objects for processing. So in you question
Salarywould be data converted from a received JSON string.JS has arrays and objects.
Objects are the most basic, they can have properties whose names can be any arbitrary string. Two forms of object property access is provided : brace and dot notation. Brace notation is universal, you specify the property name value as a string or variable value inside braces after the object name. Dot notation is a shorthand and can be used only when the name of the property has the form of a valid JS variable name.
Arrays are basic objects which have the additional feature of maintaining an ordered list of their numeric property names. You can add non numeric property names to arrays but they do not participate in any Array function.
So in you example you do not have numeric keys or property names since they contain a ‘_’ character. Since they start with a digit you cannot use dot notation and must use the brace notation to access them as explained by dystroy below.
Hoping my little lesson helps you better understand the basics.