JSON Parsing Function for Shell Scripts

When testing REST-based web services that return JSON you may decide to use a shell script with cURL commands. Some services require a call to authorize a client and a second call to perform some action. In these cases, you would need to store the returned information in variables to use in subsequent calls. This is only a simple example of why you would want a shell script to parse JSON and return a value, but the usefulness of a JSON parser goes beyond a simple example like this.

It should be noted that the following function works best for JSON objects and hasn’t been tested with JSON arrays. The tests worked reliably with properly quoted names and values. I cannot promise that this function would work on non-quoted names and values, but there is code to allow non-quoted value types.

Gets a single json element value from a json blob.

For json values (like {"key":{"k2":"val"}}) you need to first get "key"

then do an additional call with the value as the input to the function and "k2" as the argument

Example1: cityvar=$(jsonElement "city" "{\"city\":\"Seattle\"}")

Example2: cityvar=$(jsonElement "city" "{\"city\":{\"name\":\"Seattle\","county":"King"}")

countyvar=$(jsonElement "county" "$cityvar")

echo $countyvar #outputs "King" (without quotes)

jsonElement(){ #echo $1 out=$(echo $2 | awk -F"[,:]" '{for(i=1;i<=NF;i++){if($i~/'$1'\042/){print $(i+1)} } }') if [[ $out == \"\" ]]; #test if the string starts and ends in a quote then echo "${out:1:${#out}-2}" #removes first and last quotes elif [[ $out == \"\"} ]]; then echo "${out:1:${#out}-3}" #removes first and last quotes plus the curly brace else echo $out fi }

Latest Posts