Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an array element with jq?

Tags:

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"     }   ] } 
like image 587
Paul Ericson Avatar asked Mar 08 '16 19:03

Paul Ericson


People also ask

Does jq use JSONPath?

jp is a JSON processor for the command line using JSONPath (aka "a simpler jq, and with JSONPath").

How do you remove the last element of an array?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.


1 Answers

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"     }   ] } 
like image 123
jq170727 Avatar answered Sep 28 '22 02:09

jq170727