Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: delete element from array

Tags:

json

arrays

jq

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

like image 430
Vince Vince Avatar asked Oct 20 '25 08:10

Vince Vince


2 Answers

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")])
like image 50
Inian Avatar answered Oct 21 '25 23:10

Inian


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.

like image 28
peak Avatar answered Oct 21 '25 23:10

peak



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!