I'm using jq to parse some JSON. I want to check whether a property exists or not. If it exists I always want to get the first element in the array. Based on this I want to use if then ... else
.
My code looks like this:
JSON_INPUT='{"var1":[{"foo":"bar"}],"var2":[{"fooooo":"baaaaar"}]}'
VAR2=$(echo $JSON_INPUT | jq '.["var2"] | .[0]')
if [ -z "${VAR2}" ]
then
echo "does not exist"
# do some stuff...
else
echo "exist"
# do some stuff...
fi
The JSON_INPUT may contain var2
but must not. If it does not exist VAR2
will be null. But I'm not able to check for this null value. Where is the error?
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
jq normally returns with exit code 0 if the jq program and and input data are valid, regardless of the program's output. Adding the -e flag causes jq to return with exit code 1 if the output is null or false and 0 otherwise.
jq is an amazing little command line utility for working with JSON data. We've written before about how you can use jq to parse JSON on the command line, but in this post I want to talk about using jq to create JSON data from scratch or make changes to existing data.
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed , awk , grep and friends let you play with text. jq is written in portable C, and it has zero runtime dependencies.
Where is the error?
Replace
[ -z "${VAR2}" ]
with
[ "${VAR2}" = "null" ]
because jq
returns string null
if var2
is not found in JSON file.
Or use --exit-status
:
if echo "$JSON_INPUT" | jq --exit-status '.var2' >/dev/null; then
echo "exists"
else
echo "does not exist"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With