1

These are my JSON objects.

({
"0":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F86040788&amp",
"1":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F87126537&amp",
"2":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F84915833&amp",
"3":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F87317484&amp",
"4":"http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F86548283&amp"
})

I fetched them with Ajax and this is how I get to them:

data[0] to data[4].

Why is data.1, etc not working? I don't understand why I can access the objects like this data[0], because they are not arrays.

3
  • 3
    Write your code and error messages. Commented Apr 13, 2013 at 2:44
  • I'm not so sure about the round parenthesis enclosing the curly brackets. See: json.org/example.html Commented Apr 13, 2013 at 2:50
  • the round parenthesis are for JSONP. And there is no error message, unless I try to acces my objects like this: data.0. My question is why I can't? Commented Apr 13, 2013 at 3:00

3 Answers 3

3

Why is data.1, etc is not working?

Thats because data.1 is an invalid syntax according to the grammar of Javascript. Open your browsers console and try:

var obj = {};
obj[0] = "test";
obj.0; //SyntaxError: Unexpected number

I don't get why I can acess the objects like this data[0], because they are not arrays.

In javascript, arrays and map/dictionary/association array are the same thing. You can access by either object[key] syntax or object.key syntax. Only restriction is that it should be parseable by the parser (it should be an identifier), otherwise it would fail -- like the case you have. Another example:

var obj = {"test-data":1, "test": 2};
obj["test"]           // 2
obj.test              // 2
obj["test-data"];     // 1
obj.test-data         //ReferenceError: data is not defined
      //^ is a <MINUS> character, parsed as (obj.test - data)
Sign up to request clarification or add additional context in comments.

Comments

1

Working with objects: Objects and properties

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

Comments

0

because json var name could not start from digit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.