I have some web API, which response with JSON, and a shell script, which sends requests with curl and processing JSON with jq.
Response structure is the following:
{ "error": "error_message" }
- single struct.[ { "element1": "value1", "element2": "value2", "element3": "value3" } ]
- array of structs of 3 elements (fixed amount).The problem is that user may enter some data causing API response with the error. In this case, I won't be able to process the response as there is another structure.
I was trying to check if it's an error with echo ${json} | jq '. | select (.| has("error")) | has("error")'
, but this works only if it's an error response, if it's a "good" one - jq fails.
What should I do?
If you know that the responses are going to be of a specific type (an object vs an array), you could just test for that type.
$ <<<"$json" jq 'arrays' # "good" response
$ <<<"$json" jq 'objects' # "bad" response
You could add additional checks as needed.