What is the difference between "{ }" and "[ ]" brackets?

Asked

Viewed 30,488 times

14

The JSON file format uses two types of symbols to organize the data in its structure, they are:

  1. Square brackets: [ ]
  2. Keys: { }

In them it is possible to insert values of several types, see this illustration example:

{
  "Nome": "Ana",
  "Endereco": [
                {"Rua": "Rua da boiada"}, 
                {"Cidade": "Cruzeiro"}
              ],
  "Telefones": ["31991188", "39999100"]
}

My doubts are linked to these symbols mentioned above.


Doubts

I would like to know what are the differences between brackets [ ] and keys { } and what the appropriate situations would be for each of them?

  • 5

    {} is to create objects and [] to create arrays.

3 answers

18


  • {} are used to create/reference objects
  • [] are used to create/reference arrays

Basically, one can say that arrays are a list of elements, ordered without specific keys. Objects are a group of elements where each can be referenced by its key.

Objects and arrays are Javascript types, but also have representation in other languages. Object can also be called "associative array" because each value has associated a key.

Each of these guys have their own methods, which one to use depends on what you need to store/organize.

If it is necessary to have a list of names, or sequence of numbers and it is important the order in which they are, then you should use an array. You can have objects within each array. In objects it is practical to call key values of the same, so the organization is by keys and not by specific order.

Analyzing your example would be like this:

{
  "Nome": "Ana",
  "Endereco": [
                {"Rua": "Rua da boiada"}, 
                {"Cidade": "Cruzeiro"}
              ],
  "Telefones": ["31991188", "39999100"]
}

Your JSON is a 3-key object: Nome, Enderenço, Telefones.

The key Nome has a String with the value Ana.
The key Endereço has a Array as value, Array is formed by Objects.
The key Telefones has a Array string.

7

Keys { } delimit the structure of an object or whatever properties/characteristics it will have.

Square brackets [ ] Indicates that there is more than one element, it is the same array notation.

In the question example your object has three properties Nome, Endereco and Telefones..

Endereco has a collection (array) of other objects {"Rua": "Rua da boiada"}, {"Cidade": "Cruzeiro"}

Already Telefones has/points only to a simple array.

6

[] is used to create arrays indexed (i.e., they work with numbers), each item being a new "index" within the array, it would be almost the same as Array()

The {} is an object, looks a little like array, but it is not, the items within it are associated by names (keys), it does not preserve the order the items were added to. It would be almost the same as new Object

Browser other questions tagged

You are not signed in. Login or sign up in order to post.