Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ remove objects based on key value

Tags:

json

jq

I'm trying to delete objects from a JSON payload if they have a key with a specific value

{
  "data": [
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "DTU1GGfR0eU15hv6KiV_bg6FOJXfUWz4TjIq1H7TGy4",
      "timestamp": "2020-08-28T01:29:46.000000Z"
    },
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "l3EQR6AJ6R1qE1meHyafDnNF8vJ-X-rH1pujxQRTds4",
      "timestamp": "2020-08-28T00:50:44.000000Z"
    },
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "5fQJY9MprH9b3IstVU1SdfBteUWoF_sdsVuiARPBtTY",
      "timestamp": "2020-08-27T19:01:48.000000Z"
    },
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "0M0fudEmzW9dmAsO3dcWT286tTL6wTX9sllXtsyz-0Q",
      "timestamp": "2020-08-27T18:15:17.000000Z"
    }
  ]
}

I want to delete the entire object where .data[].hash == 0M0fudEmzW9dmAsO3dcWT286tTL6wTX9sllXtsyz-0Q to produce:

{
  "data": [
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "DTU1GGfR0eU15hv6KiV_bg6FOJXfUWz4TjIq1H7TGy4",
      "timestamp": "2020-08-28T01:29:46.000000Z"
    },
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "l3EQR6AJ6R1qE1meHyafDnNF8vJ-X-rH1pujxQRTds4",
      "timestamp": "2020-08-28T00:50:44.000000Z"
    },
    {
      "account": "12xUoMKwf12ABjNx4VCvYcNkX79gW1kzz2JnBLxkFbjswRczRvM",
      "gateway": "113kQU96zqePySTahB7PEde9ZpoWK76DYK1f57wyhjhXCBoAu88",
      "hash": "5fQJY9MprH9b3IstVU1SdfBteUWoF_sdsVuiARPBtTY",
      "timestamp": "2020-08-27T19:01:48.000000Z"
    }
  ]
}

Is this possible to do? The size of the object can vary and have many different keys in the payload. The one thing that is constant and unique is the .data[].hash key

Thanks

like image 342
Nick Hatfield Avatar asked Jul 17 '26 06:07

Nick Hatfield


1 Answers

You can use del along with select function such as

jq 'del(.data[] | select(.hash == "0M0fudEmzW9dmAsO3dcWT286tTL6wTX9sllXtsyz-0Q"))'

Demo

like image 108
Barbaros Özhan Avatar answered Jul 19 '26 21:07

Barbaros Özhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!