mmlb
mmlb

Reputation: 980

How do I remove elements from array in a JSON object containing a value

Please note that this post is tagged jq, I am not trying to do this with javascript at all.

I have an object that has an array as one of its fields. I'd like to remove the elements from the object's array that match a criteria, but keep the object around. I've looked around and I've only been able to spot snippets of returning just the array that happens to have less items now.

Here's an example:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    },
    {
      "id": null,
      "msg": "done"
    }
  ]
}

and I'd like to get back the following:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    }
  ]
}

Note: Just in case this will affect the answer I'm really only interested in the last element. I plan to build up a new object in a following pipe stage like:

jq '$answer | {bar:.foo, event: .events[-1].msg}`

I have tried both

select(.events[].id != null)

and

del(.events[], select(.id == null)))

with no luck.

Upvotes: 3

Views: 5892

Answers (2)

peak
peak

Reputation: 116880

When in doubt (sometimes del(...) is a bit tricky), you can always use map(select(...)), e.g. in the present case:

.events |= map(select(.id != null))

or perhaps even:

.events |= map(select(.id))

Upvotes: 0

Inian
Inian

Reputation: 85800

I think you are probably looking for jq filter as below. The expression .events[] | select(.id == null) returns the key to the object where the id value is null and del() deletes that key/value pair.

jq 'del(.events[] | select(.id == null))'

As a side note, if you just want to delete an element just by index, you could just use as below. The example below deletes the element from index 2, the array actually starts at 0.

jq 'del( .events[2] )'

But remember this way is not recommended for your original problem, since you wouldn't know which index of your key would contain the null value.

Upvotes: 5

Related Questions