Conditional output using jq

Viewed 394

I have JSON input like the following.

  • {"value":{"error":"no such element","message":"no such element: xxx"}
  • {"value":null}

I want to use jq to return with an exit status of 0 (print nothing) for the second case, and print no such element: xxx to stderr and return an exit status of 1 for the first case.

How can I achieve this in jq?

2 Answers

One way to specify the exit code is with the built-in filter halt_error. To meet your specifications as I understand them, you could thus write:

 .value
 | if . then .error | halt_error(1)
   else null | halt_error(0)
   end

See the jq manual for details and to explore variations (e.g. to add "\n").

The way I understand this question (and also what I was looking for before coming across this) is that you want the jq program to exit with different status codes depending on which type of input is read first.

file.json

{"value":{"error":"no such element","message":"no such element: xxx"}}
{"value":null}

Using the builtin halt and halt_error, you can accomplish this:

jq -n 'inputs | .value | if .error then "\(.message)\n" | halt_error(1) else halt end' < file.json

The only difference between this and the current answer is that jq will actually quit after it reads the first input, and will ignore the rest of the file.

Related