Vince Vince
Vince Vince

Reputation: 55

jq: delete element from array

I have this JSON file and want to delete an element from an array:

{
"address": "localhost",
"name": "local",
"vars": {
    "instances": [
        "one",
        "two"
    ]
  }
}

I am using this command:

jq 'del(.vars.instances[] | select(index("one")))' data.json

The output is:

{
"address": "localhost",
"name": "local",
"vars": {
    "instances": [
        "two"
    ]
  }
}

So it works as expected, but only with jq v1.6. With jq v1.5 I get this error:

jq: error (at data.json:20): Invalid path expression near attempt to access element 0 of [0]

So what am I doing wrong? Is this a bug or a feature of v1.5? Is there any workaround to get the same result in v1.5?

Thanks in advance

Vince

Upvotes: 4

Views: 3375

Answers (2)

Inian
Inian

Reputation: 85800

One portable to work with on both versions would be,

.vars.instances |= map(select(index("one")|not))

or if you want to still use del(), feed the index of the string "one" to the function as below, where index("one") gets the index 0 which then gets passed to delete as del(.[0]) meaning to delete the element at zeroth index.

.vars.instances |= del(.[index("one")])

Upvotes: 6

peak
peak

Reputation: 116880

The implementation of del/1 has proven to be quite difficult and indeed it changed between jq 1.5 and jq 1.6, so if portability across different versions of jq is important, then usage of del/1 should either be restricted to the least complicated cases (e.g., no pipelines) or undertaken with great care.

Upvotes: 3

Related Questions