Home > Software design >  In jq, what's the difference between `.my_array` and `.my_array[]`?
In jq, what's the difference between `.my_array` and `.my_array[]`?

Time:09-23

I'm new to JQ and I'm having trouble wrapping my head around the return types of JQ's filters when applied to arrays.

Specifically: What's the difference between .my_array and my_array[]?

The first example returns an array:

$ echo '{"my_array":[{"id":1},{"id":2}]}' | jq '.my_array'
[
  {
    "id": 1
  },
  {
    "id": 2
  }
]

While the second example seems to return each element of the array:

$ echo '{"my_array":[{"id":1},{"id":2}]}' | jq '.my_array[]'
{
  "id": 1
}
{
  "id": 2
}

What's the precise difference between "filter that returns an array" and "filter that returns each element of the array", and why does JQ consider them different?

CodePudding user response:

Perhaps the key concept you have not grasped is that of a "stream". jq can be thought of as a stream-oriented language so you might find the following helpful:

https://github.com/pkoppstein/jq/wiki/A-Stream-oriented-Introduction-to-jq

Disclosure: I am the author.

CodePudding user response:

Consider a filter that would do something with the result of each of your two filters. This might make it clearer than simply seeing the value(s) written to standard output.

First, we create an object from the single array value produced by .my_array. The entire array becomes the value of the key x.

% echo '{"my_array":[{"id":1},{"id":2}]}' | jq '{x: .my_array}'
{
  "x": [
    {
      "id": 1
    },
    {
      "id": 2
    }
  ]
}

Next, we create two objects, one for each object value produced by .my_array[].

% echo '{"my_array":[{"id":1},{"id":2}]}' | jq '{x: .my_array[]}'
{
  "x": {
    "id": 1
  }
}
{
  "x": {
    "id": 2
  }
}
  • Related