Q1: When defining object literals in javascript, the keys may include quotes or not. There is no difference except that quotes allow you to specify certain keys that would cause the interpreter to fail to parse if you tried them bare. For example, if you wanted a key that was just an exclamation point, you would need quotes:
a = { "!": 1234 } // Valid
a = { !: 1234 } // Syntax error
In most cases though, you can omit the quotes around keys on object literals.
Q2: JSON is literally a string representation. It is just a string. So, consider this:
var testObject = { hello: "world" }
var jSonString = JSON.stringify(testObject);
Since testObject
is a real object, you can call properties on it and do anything else you can do with objects:
testObject.hello => "world"
On the other hand, jsonString
is just a string:
jsonString.hello => undefined
Note one other difference: In JSON, all keys must be quoted. That contrasts with object literals, where the quotes can usually be omitted as per my explanation in Q1.
Q3. You can parse a JSON string by using JSON.parse
, and this is generally the best way to do it (if the browser or a framework provides it). You can also just use eval
since JSON is valid javascript code, but the former method is recommended for a number of reasons (eval has a lot of nasty problems associated with it).