Home > database >  Swap first and second item from json array?
Swap first and second item from json array?

Time:03-08

Suppose I have an array : ["1","2","3"]. How can I swap the first element 1 with the later one which is 2 ?

That is the end result to be ["2","1","3"]

CodePudding user response:

As jq is tagged, how about the reverse function applied to the sublist containing the first two elements

jq '.[:2] |= reverse'
["2","1","3"]

Demo

CodePudding user response:

More generically, if more prosaically:

def swap(i;j): .[i] as $t | .[i]=.[j]|.[j]=$t; 
swap(0;1)
  • Related