Home > Net >  jq utility - extract certain json blocks
jq utility - extract certain json blocks

Time:03-22

I am formatting the json output from curl command using jq utility. I am not able to find a way to extract a json block by position.That is to say if I want to print just the last json block or a random json block like 5th or 6th or 5th & 6th only, is there a jq option or a way to achieve this please?

JSON array looks like this

[
  {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3"
  },
  {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3"
  },
  {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3"
  },
  {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3"
  }
]

CodePudding user response:

Last: last

5th: .[4]

6th: .[5]

5th and 6th (as array) .[4:6]

5th and 6th (as array) [ .[4], .[5] ]

5th and 6th (as stream) .[4:6][]

5th and 6th (as stream) .[4], .[5]

CodePudding user response:

Last: .[-1]

n-th, where $n is specified on the command line (0-based indexing): jq --argjson n $n '.[$n]'

$m-th and $n-th (with 0-based indexing): '.[$m, $n]'

An element chosen pseudo-randomly (assuming a bash or bash-like shell and that the array is not too long):

jq --argjson prn $RANDOM '
  if length > 32767 then "Sorry - this algorithm is too simplistic." | error
  else .[$prn % length]
  end
'  

An alternative way to make a pseudo-random choice without assuming a bash-like environment:

jq '
  if length > 1e6 then "Sorry - this algorithm is too simplistic." | error
  else 
   (now|tostring|sub(".*[.]";"")|tonumber) as $n
   | .[$n % length]
  end'
  • Related