6 ms·
I never understood why the double quotes around property names are mandatory. For example, in JavaScript, I can write { foo: 1, bar: 2 } but JSON syntax i
by greenyoda 10y ago
I never understood why the double quotes around property names are mandatory. For example, in JavaScript, I can write
{ foo: 1, bar: 2 }
but JSON syntax insists on
{ "foo": 1, "bar": 2 }
This makes JSON less easily readable by humans, and harder to write or edit by hand.
Anyone know why JSON was designed this way?
- shill 10y agoMy assumption is that quotes are needed for keys with spaces. > x = {} > x["foo bar"] = 1 > x { 'foo bar': 1 }
- Retra 10y agoThat only explains why they are permitted, not why they are mandatory.
- xrstf 10y agoBecause using certain keys could break your JavaScript (and JSON was designed to be a subset), like { delete: "me" } If you don't want to keep a list of known keywords around, just insisting on quotes is the easier way. [EDIT: See also this YouTube video, where Douglas Crockford explains it himself: https://youtu.be/-C-JoyNuQJs?t=5m https://youtu.be/-C-JoyNuQJs?t=5m]
- yepperino 10y agoUnquoted keywords are valid ES5.1 object properties. alert(JSON.stringify({delete: "me", for: 1, var: 2})); results in: {"delete":"me","for":1,"var":2} The only browser it does not work in is IE8 and earlier.
- lucian1900 10y agoJSON significantly predates ES 5.1
- jerluc 10y agoI'm no expert, but I'd imagine fully dropping the quotes wouldn't allow you to use the same syntax as a map/dictionary in Javascript, whereby the keys could be [almost] any type, and string keys could contain characters such as - or even : which otherwise would prove ambiguous to a Javascript parser.
- nemild 10y agoI don't know the history of why design decisions were made in JSON, but one might be the allowance for spaces in keys and mirroring the usage within arrays (where commas and spaces may be used in a string, but shouldn't be confused with a record separator). Per my other comment, there are a variety of plugins on the editor side that will make JSON look like this (e.g., vim-json ). To write out to JSON from that format, you can obviously just write a plugin (in JS this is one line).
- Feneric 10y agoThe stricter syntax allows JSON to be directly parsed outside of JavaScript in other languages like Python. This is a nice feature and one of the selling points of JSON.
- usrusr 10y agoJSON values low variance between different representations of logically equivalent documents. It's not a primary concern (e.g. the explicit lack of key order allows a lot of variance), but it seems to trump syntax convenience just about everywhere except whitespace. Going all unquoted-keys would also be low variance, but this would restrict keys from "any string" to "valid javascript identifiers" or something bespoke in between.