JSON

Files in JSON format have the same syntax rules of the . But they also need to adhere to some additional rules, which are not needed in Javascript object literals:

structures available

In JSON we can structure data in two different ways, such as arrays and objects. All JSON files represent one of two structures:

  1. On object, that is, a list of key/value pairs.
  2. A collection of elements, which is known as an array or array.

This means that you cannot put a primitive value (numbers, strings, booleans) as it is as a valid JSON, but it will have to be inside an allowed structure, like an object or an array.

Braces to represent objects

JSON files representing objects always begin with a starting brace { and end with a closing brace }.

{ “id”: 44, “game”: “Settlers of Catan”, “author”: “Klaus Teuber”, “ages”: “10+” }

Brackets to represent arrays

JSON files that represent a list of values, that is, an array, start with .

The above array is valid JSON, but it is more common to use complex values ​​in the cells of the array. In fact, within a checkbox we could have any other valid JSON value, even other complex objects.

Values ​​representable with JSON

All values ​​that we can find in JSON represent one of these possibilities:

  1. A primitive value, which can be of various Javascript types, numeric, string, and boolean (true / false).
  2. Arrays, that is, a sequence of values ​​separated by commas. In arrays we use square brackets to delimit the beginning and end of the values ​​they contain.
  3. Objects, i.e. other JSON elements with key/value pairs.
  4. In addition, the null value is also valid.
See also  Distribute transpiled Javascript or not (ES5 or ES6) according to browser with Webpack

Use of double quotes

Always use double quotes around strings and object attribute names.

This point is important, because the Javascript syntax for object literals allows you to place property names with and without quotes, whereas in JSON we are forced to always place property names with double quotes.

{ “id”: 1, “name”: “New potatoes”, “description”: “Potatoes harvested this year”, “available”: true }

In the code above, the property names “id”, “name”, etc. they must be placed with double quotes. All object attribute names must necessarily have quotes. Additionally, strings must also be placed with double quotes.

Commas to separate key/value pairs

Each element of the JSON object is separated from the next with a comma (,). But there must not be a comma after the last element in any case (Javascript would allow it).

UTF-8 required

All JSON-encoded files are required to be UTF-8 encoded. The transferred file in a JSON must necessarily be encoded as UTF8 so that there are no display problems of the characters contained in it.

Loading Facebook Comments ...
Loading Disqus Comments ...