What is the difference between {active: "yes"} and {"active": "yes"}?
I've used FireBug to test the two cases and they seem pretty similar by result:
>>> var x = {"active": "yes"}
>>> x.active
"yes"
>>> var x = {active: "yes"}开发者_开发知识库
>>> x.active
"yes"
But I'm pretty sure there is some difference between these two, maybe even performance related difference. Bottom line - I'd like to know if there is a difference between {active: "yes"} and {"active": "yes"}.
Both are valid. However there are certain keywords you cant use like delete
so in order to avoid that you wrap them in quotes so they are not treated literally by the ECMAScript parser and instead are explicitly specified as strings.
Additionally, the JSON spec requires that keys have quotes around them:
A string begins and ends with
quotation marks
So {key:'value'}
is not valid JSON but is valid JS, while {"key":"value"}
is valid JS and JSON.
Examples of keywords and invalid/ambiguous keys:
>>> ({delete:1})
SyntaxError: Unexpected token delete
>>> ({'delete':1})
Object
Another example:
>>> ({first-name:'john'})
SyntaxError: Unexpected token -
>>> ({'first-name':'john'})
Object
>>> ({'first-name':'john'})['first-name']
"john"
Both are valid JavaScript (although some names can only be used quoted, active
isn't among them).
The latter is invalid JSON (quoted names are mandatory in JSON).
Every valid JSON is also valid JavaScript but not every valid JavaScript is also valid JSON as JSON is a proper subset of JavaScript:
JSON ⊂ JavaScript
JSON requires the names of name/value pairs to be quoted while JavaScript doesn’t (as long as they are not reserved keywords).
So your first example {"active": "yes"}
is both valid JSON and valid JavaScript while the second example {active: "yes"}
is only valid JavaScript.
In JavaScript, {"active": "yes"}
, {'active': "yes"}
, {"active": 'yes'}
and {active: 'yes'}
are all the same -- if you are using a reserved keyword (as meder points out), you must quote the key -- otherwise, the key does not need to be quoted.
In JSON, on the other hand all keys and values must be quoted with "
.
{"active": "yes"}
is valid JSON.
{'active': "yes"}
, {"active": 'yes'}
and {active: 'yes'}
are not.
If you are using this for JSON, the name (active
) must be enclosed in quotes. It will still work in JavaScript without it, but it's technically malformed JSON.
See: http://json.org/
Note that the object
, requires a string
for the name (the bit before the colon).
精彩评论