36

I'm trying to figure out how to remove an array element from some JSON using jq. Below is the input and desired output.

jq .Array[0] 

outputs the array element I want.

{
      "blah1": [
        "key1:val1"
      ],
      "foobar0": "barfoo0",
      "foobar1": "barfoo1"
    }

But how do I re-wrap this with:

{
  "blah0": "zeroblah",
  "Array": [

and

  ]
}

Input:

{
  "blah0": "zeroblah",
  "Array": [
    {
      "blah1": [
        "key1:val1"
      ],
      "foobar0": "barfoo0",
      "foobar1": "barfoo1"
    },
    {
      "blah2": [
        "key2:val2"
      ],
      "foobar2": "barfoo2",
      "foobar3": "barfoo3"
    }
  ]
}

Desired output:

{
  "blah0": "zeroblah",
  "Array": [
    {
      "blah1": [
        "key1:val1"
      ],
      "foobar0": "barfoo0",
      "foobar1": "barfoo1"
    }
  ]
}
Paul Ericson
  • 777
  • 2
  • 7
  • 15
  • Do you want to delete just `Array[1]` or all elements of `Array` past the first, i.e., what should the output be if `Array` has more than two elements? – jwodder Mar 08 '16 at 19:49
  • In this case there are only two array elements and I want to delete the second one. But more generically, I'm trying to understand how jq would allow for selective array element control. Maybe next time I want to delete array elements 1,3,5 and 11. – Paul Ericson Mar 08 '16 at 20:00

2 Answers2

56

Regarding the second part of Paul Ericson's question

But more generically, I'm trying to understand how jq would allow for selective array element control. Maybe next time I want to delete array elements 1,3,5 and 11.

To delete elements 1,3,5 and 11 just use

del(
    .Array[1,3,5,11]
)

but in general you can use a more sophisticated filter as the argument to del. For example, this filter removes the elements within .Array whose .foobar2 key is "barfoo2":

del(
    .Array[]
  | select(.foobar2 == "barfoo2")
)

producing in this example

{
  "blah0": "zeroblah",
  "Array": [
    {
      "blah1": [
        "key1:val1"
      ],
      "foobar0": "barfoo0",
      "foobar1": "barfoo1"
    }
  ]
}
jq170727
  • 13,159
  • 3
  • 46
  • 56
  • Just in case someone is wondering how to do the same inside a top-level array, the command will look like the following: `del(.[] | select(.key == "value"))` – Andrew Tatomyr May 19 '23 at 08:59
19

In this particular case, the simplest would be:

del(.Array[1])

More generally, if you wanted to delete all items in the array except for the first:

.Array |= [.[0]]
peak
  • 105,803
  • 17
  • 152
  • 177