0

I have this JSON code :

{
    "query": {
        "pages": {
            "-1": {
                "ns": 0,
                "title": "StackOverflow",
            }
        }
    }
}

I parsed it into a JSON object :

data = JSON.parse(jsonString);

Why to access the object -1 I must do data.query.pages[-1] not data.query.pages.-1. In this example pages is not an array but an object.

Hunsu
  • 3,281
  • 7
  • 29
  • 64

3 Answers3

8

It's not an array, it's an object. Both object["name"] and object.name are identical ways of accessing a property called name on the given object.

You cannot access an object property with object.-1, simply because that's a syntax error, the same way you can't use object.+1 or object.[1 or object./1. They're all valid names for a property of an object, but they're syntactically invalid when using object.propertyName syntax.

The other caveat is that you cannot have property names which are integers. Setting or getting object[-1] is identical to object["-1"] as the property name is converted to a string. It would be identical to accessing object.-1 if that were valid syntax.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • [this is a good resource](https://github.com/airbnb/javascript#properties), though i suppose it doesn't mention anything about numbers – ddavison Jul 18 '14 at 20:15
2

You can't do data.query.pages.-1 for the same reason you can't do var -1;: -1 is not a valid identifier.

But that's not a problem.

foo.bar       // Access member bar of object foo

is just a shortcut for

foo["bar"]    // Access member bar of object foo

so you can do

data.query.pages["-1"]

You could even do

data["query"]["pages"]["-1"]
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

Bracket notation has nothing to with arrays, it's just another way to access properties. In fact, the reason why we can only use bracket notation for arrays is because of the evaluation rules: To use dot notation, the property name must be a valid identifier name.

Or simply put:

You can only use dot notation if the property name would be a valid variable name or a reserved word.

And -1 doesn't fall in that category (you can't do var -1 = 'foo'; for example).


Examples for invalid identifier names:

  • 0foo, -foo, &bar
    anything that doesn't start with a letter, _ or $

  • foo-bar, foo+bar, foo bar
    anything that contains something that is not a letter, a digit, _ or $ (or fall into specific unicode ranges, see the spec).

However, using reserved words is possible, even though they can't be used as variables:

foo.if // valid
var if = 42; // invalid
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143