0

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?

Community
  • 1
  • 1
emeryville
  • 49
  • 1
  • 6
  • 2
    _"2012_08" is the year month combination and that cannot change to be stored as a string._ - It is already a string: numbers can't have underscores in them, and the value is in double-quotes. (It's just not a valid identifier for use in object property "dot notation".) – nnnnnn Oct 11 '12 at 06:56
  • 1
    Btw, your problem has nothing to do with JSON, I edited your question accordingly. – Felix Kling Oct 11 '12 at 07:02

2 Answers2

6

All object properties can be accessed using the brace notation.

Use

var augsalary =  salary['2012_08'];

Note that if you want it as an integer (and cannot change the JSON to send numbers) you may use :

var augsalary =  parseInt(salary['2012_08'], 10);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

First, your Javascript code is invalid, perhaps you meant

var Salary = {
  "2012_08":"5555",
  "2012_09":"6666",
  "2012_10":"7777"
}
var augsalary =  salary.2012_08;

Second, an all too common confusion is to talk of JSON objects. Salary is NOT a JSON object, it is a JavaScript object. JSON is a notation for expressing 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 Salary would 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.

Community
  • 1
  • 1
HBP
  • 15,685
  • 6
  • 28
  • 34