Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the "key" part in a JS hash/dict be a string?

In most JSON serializers/deserializers, the "key" part in a javascript dictionary/hash array is written as a string.

What is the benefit of using a string as the key as opposed to just typing the intended name in?

For example, say I define two objects k1 and k2 like so:

var k1 = { a: 1, b: 2, c: 3 };          // define name normally
var k2 = { "a": 1, "b": 2, "c": 3 };    // define name with a string

And I then ran the following tests:

alert(k1 == k2);                   // false (of course)

alert(k1.a == k2.a);               // true
alert(k1["b"] == k2["b"]);         // true

alert(uneval(k1));                 // returns the k1 object literal notation.
alert(uneval(k2));                 // returns the same string as above line.

alert(uneval(k1) == uneval(k2));   // true

So what's the point of having the keys be in double-quotation marks (a string) as in the way k2 was defined instead of just typing the key names in as in the way k1 was defined?


I just saw this over at Ajaxian pointing to Aaron Boodman's blog entry:

chromium.tabs.createTab({
 "url": "http://www.google.com/",
 "selected": true,
 "tabIndex": 3
});

Since he also use camel case for tabIndex, I don't see any point in using a string at all.

Why not:

chromium.tabs.createTab({
 url: "http://www.google.com/",
 selected: true,
 tabIndex: 3
});

Why would a JS ninja follows the convention of turning url, selected and tabIndex into a string?

like image 308
chakrit Avatar asked Apr 07 '09 18:04

chakrit


Video Answer


1 Answers

Because JSON is a subset of the actual JavaScript literal syntax. For simplicity in implementing JSON parsers, double quotes are always required around strings, and as keys in JSON are strings, they are required there.

Not all legal JavaScript is legal JSON. While you can define object literals in JavaScript without the quotes, if you want interoperable JSON, you're going to need to put them in.

like image 51
Brian Campbell Avatar answered Sep 19 '22 21:09

Brian Campbell