Arrays and Objects

When working with JSON and trying to use transformations on JSON, it is important to understand the difference between Arrays and Objects in JSON.

Arrays:

 "myArray": [
    "a",
    "b",
    "c",
    "d"
]

Here we have defined a key ("myArray") that contains an array defined by the square brackets []. Between the square brackets, you can insert values that are separated by a comma, except the last entry. With this sample data we can do the following transformation:

arrayAccess: myArray[2]
"arrayAccess": "c"

Note that arrays can contain many different types of data like strings, numbers, and even other arrays or objects.

Objects:

"myObject": {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4
  }

Here the key ("myObject") is followed by the curly brackets {}. They contain further key/value pairs separated with commas except for the last entry. These values can be accessed like the following transformation:

objectAccess: myObject.b
"objectAccess": 2

Here you have to reference an objects key, to find its value. In this example, we access “myObject”‘s key named “b” to have the value “2” returned.

While these are some simple examples of objects and arrays, they can intertwine like the example below, where we have an array that contains objects and an object that contains another array.

{
  "mySecondArray": [
    {
      "object1": "some data",
      "object2": "more data"
    },
    {
      "alsoAnArray": [
        23,
        45,
        75
      ]
    }
  ]
}

This can be accessed with the following transformations:

{
  access1: mySecondArray[0].object1,
  access2: mySecondArray[1].alsoAnArray[1]
}
{
  "access1": "some data",
  "access2": 45
}

As briefly touched upon earlier, you can nest objects within arrays, and arrays within objects but you can also nest objects within objects and arrays within arrays. Therefore, it is important to know the different types in JSON when trying to do your transformations. Note that everything is 0 indexed meaning the first data point in any array or object is at index 0 i.e. alsoAnArray[0] is the first entry and has the value 23 where the second entry is index 1 (alsoAnArray[1]) an so forth.