开发者

Should I be using strings to delimit the object names in JSON?

I have seen a tutorial that has the following JSON:开发者_如何学运维

{

   books:[{title:"frankenstein"},{title:"Moby Dick"}]

}

When I put the above into js.bin I get an error saying that it expect a string and saw books. So I changed it to the below and it works...

{

   "books":[{"title":"frankenstein"},{"title":"Moby Dick"}]

}

However if I change the first code snippet from above to the below it works.

var p = {

   books:[{title:"frankenstein"},{title:"Moby Dick"}]

};

What im wondering is:

1) Do you really have to use speech marks for the variable name in JSON (the example I saw is incorrect if you do).

2) Is there a relationship between JSON and javascript object notation?


Do you really have to use speech marks for the variable name in JSON (the example I saw is incorrect if you do).

Yes.

Is there a relationship between JSON and javascript object notation?

Yes. JSON is an abbreviation of JavaScript Object Notation (but I don't think that is what you mean).

The relationship between JSON and JavaScript is that JSON is (very nearly) a subset of the syntax used to create literals in JavaScript.

JSON is heavily simplified which makes it slightly less convenient to handcraft (don't handcraft JSON, use a library!) but makes the specification smaller and parsers easier to write.

Most of the simplifications are down to exceptions being removed.

For example:

In JavaScript, an object literal key can be an identifier (then insert a detailed explanation about what makes a valid identifier in JS here) or a string. In JSON an object key must be a string.

In JavaScript, a string may be delimited by either single or double quotes. In JSON, a string must be delimited by double quotes.


JSON requires that property names be quoted with double-quote characters. Such quoting is not required in JavaScript for object literal expressions. In that respect, JSON is strict in comparison. JavaScript allows property names to be unquoted if they take the form of valid identifiers, and then only if they're not reserved words.

JSON was definitely derived from the object literal syntax in JavaScript, but (mostly in order to make parsing a little simpler) it is more strict. For example, property values in JSON cannot be functions.


If you speak of JSON as the data-interchange format, then yes, the names need to be quoted properly.

If you speak of “JSON” as the object syntax literal in JavaScript, then no, you don’t need to escape them unless they are a keyword in JavaScript.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜