A short JSON Primer

One of the things that newcomers to JSON ask is, when do I use hard brackets and when do I use curly braces?
Curly braces, “{” and “}”, encapsulate one or more unique key value pairs. Keys are paired to corresponding values with a colon and multiple sets of key-value pairs are separated by commas. For instance, {“foo”:”A”,”bar”:”B”} is perfectly valid. Here one sees two key-value pairs and each key is unique within the set of curly braces. However, this example {“foo”:”A”,”foo”:”B”} is invalid because the key name of “foo” is repeated.

Hard brackets, “[” and “]”, encapsulate values without named keys. This would be a valid arrangement: [“A”,”B”]. This is simply a standard array with no explicit keys named. Similarly, [“A”,”A”] is also valid. These are not repeating keys because the keys aren’t being explicitly set in this array. Only the values are.

How would you list out key-value pairs with repeating keys, like {“boo”:”A”,”boo”:”B”}? Treat this as an array of keys: [{“foo”:”A”},{“foo”:”B”}].

Each key-value pair is encapsulated by curly braces, separated by a comma, and then treated as an array of elements by encapsulating the whole by hard brackets. It is necessary to break these keys into an array because the key names cannot be duplicated within a single set of curly braces. If the key names are unique, the keys could have been encapsulated together, as in {“foo”:”A”,”bar”:”A”}.

What if you had a single object with two properties, color and shape? This would be two associated key value pairs:
{“color”:”red”,”shape”:”square”}

What if you had two of these objects? Then you would have an array of associated key value pairs:
[{“color”:”red”,”shape”:”square”}, {“color”:”green”,”shape”:”circle”}]

Each set of curly braces encapsulates a set of unique keys separated by comma. Each set of curly-braced key-value pairs are themselves elements of a non-keyed (just a normal) array, which is why the hard brackets surrounding them are required.

Note, since an array is allowed to have only one element, you could optionally encapsulate that single element with brackets: [{“color”:”red”,”shape”:”square”}]

I hope this makes understanding when to use curly braces and brackets more straightforward. You can find a useful JSON validator at http://jsonlint.com/.

Learn more about us and who we are here: http://eimagine.com/meet-our-team/.

Leave a Reply

Your email address will not be published. Required fields are marked *