10

I have the following JSON file inp.json:

{
 "x": 0,
 "tx": [
  {
   "id":  "a",
   "t" : "t for a"
  },
  {
    "id": "b",
    "t": "t for b"
  }
 ]
}

I would like to extract the value of the first occurance of the key "t" within "tx".

I tried

jq -r .tx <inp.json | jq -r '[0].t'

but got the error message

assertion "cb == jq_util_input_next_input_cb" failed: file "/usr/src/ports/jq/jq-1.6-1.x86_64/src/jq-1.6/src/util.c", line 371, function: jq_util_input_get_position

UPDATE: I also tried the variations

... | jq -r '.[0]t'

and

... | jq -r '.[0].t'

but the former gave the error message jq: error: syntax error, unexpected IDENT, expecting $end, and the latter the same error as my original attempt.

ccpizza
  • 8,241

1 Answers1

15

The -r option should not be used if the output will be fed into another JSON parser; only the last jq in the pipeline should use it – otherwise you risk feeding non-JSON data into the second jq instance.

Your last example with .[0].t seems correct and works with jq 1.6.

$ cat json | jq '.tx' | jq -r '.[0].t'
t for a

But this can be simplified to a single jq invocation, first incrementally to:

$ cat json | jq -r '.tx | .[0].t'
t for a

and then finally to:

$ cat json | jq -r '.tx[0].t'
t for a
grawity
  • 501,077