Search code examples
jsonparsingjqmin

Map on conditional produces jq: error Cannot iterate over null (null)


I want to get the minimum value of each nested refpos that's associated with GRCH38.

An example .refpos looks like this :

[
  {
    "name": "_alt_a5760de0b8c517ac3d2929ec9455ac640b540f5a_0"
  },
  {
    "name": "GRCH38#0#chr19",
    "offset": "23803754"
  },
  {
    "name": "GRCH38#0#chr19",
    "offset": "23803764"
  },
  {
    "name": "GRCH38#0#chr19",
    "offset": "23803796"
  },
  {
    "name": "GRCH38#0#chr19",
    "offset": "23803828"
  }
]

Here's a command that prints all offsets associated with GRCH38: vg view -aj ${EXPERIMENT_NAME}.gam | jq -r 'select(.refpos) | .refpos[] | if .name=="GRCH38#0#chr19" then .offset else empty end ' >${EXPERIMENT_NAME}.experiment.tsv

e.g.

23803754
23803764
23803796
23803828

But I don't want all the offsets, I want just one. To do so, I've tried a command like the following:

vg view -aj ${EXPERIMENT_NAME}.gam | jq -r 'select(.refpos) | map(.refpos[] | if .name=="GRCH38#0#chr19" then .offset else empty end | tonumber) | min' >${EXPERIMENT_NAME}.experiment.tsv

But this produces the error in the title:

jq: error (at :1): Cannot iterate over null (null)

How can I structure the command so that I get the minimum value of this set of values, instead of an error?


Solution

  • Use select to filter, tonumber to convert, and min to aggregate:

    jq '.refpos | map(select(.name == "GRCH38#0#chr19").offset | tonumber) | min'
    
    23803754
    

    Demo