简体   繁体   中英

JSON Attribute Best Practice

Usually, what I see is {"attribute":241241}

but writting this does exactly the same thing : {attribute:241241} .

Is {attribute:241241} considered bad practice and should be avoided or not?

{attribute:241241} does not validate using JSONLint , so yes, it is bad practice and should be avoided.

Further, if you look at the JSON spec at json.org , you will find that for objects the first value is always a string (indicated by double quotes).

As per the specification here , the names in name/value pairs must be of type string .

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

The JSON specification requires that keys be quoted, so the second form isn't valid JSON.

As Snakes and Coffee noted, it is a valid Javascript object literal (on which JSON is based), and some JSON parsers will accept it anyway. So it may work in some cases, but sooner or later you'll run into a perfectly functional JSON parser that rejects your non-quoted keys because they aren't valid per the spec.

You are confusing JSON with Object literal syntax, in Javascript doing

var o = {
    "attribute":241241
};

is not JSON, but object literal. And yes, the quotes are useless there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM