Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MarcBittner/76ea941ae8221283f3f5f987db74abd3 to your computer and use it in GitHub Desktop.
Save MarcBittner/76ea941ae8221283f3f5f987db74abd3 to your computer and use it in GitHub Desktop.
json_demo.sh
#!/usr/bin/env bash
requireProgram() {
local functionName debugOutput
unset ${functionName} ${debugOutput}
functionName="${FUNCNAME[0]}"
debugOutput=1
command -v ${1} >/dev/null 2>&1 &&
{
echo >&2 "${functionName} requires ${1} and it is installed."
return 0
} ||
{
echo >&2 "${functionName} requires ${1} but it's not installed. Aborting."
return 1
}
}
replaceJson() {
local key Vallue
local DebugOutput=0
while [[ ${1} ]]; do
case "${1}" in
--json)
json=${2}
shift
;;
--key)
key=${2}
shift
;;
--value)
value=${2}
shift
;;
--debug)
DebugOutput=1
;;
*)
echo "Unknown parameter: ${1}" >&2
return 1
;;
esac
if ! shift; then
echo 'Missing parameter argument.' >&2
return 1
fi
done
if [[ -z ${key} || -z ${value} || -z ${json} ]] \
; then
echo "${FUNCNAME}: one or more variables are undefined"
return 1
fi
datestamp="$(date +%s)"
[[ DebugOutput -ne 0 ]] && echo -e "\nkey: ${key}"
[[ DebugOutput -ne 0 ]] && echo -e "\nvalue: ${value}"
[[ DebugOutput -ne 0 ]] && echo -e "\njson_input: \n${json}"
# Validate JSON
if ! echo "$json" | jq empty; then
echo "Invalid JSON input"
return 1
fi
# Check for nested objects or arrays
if echo "$json" | jq 'paths | select(length > 1)' | grep -q '.'; then
echo "JSON contains nested objects or arrays"
return 1
fi
local modified_json=$(echo "$json" | jq --arg key "$key" --arg value "$value" '
.[$key] |= $value
')
echo -e "\nModified JSON: \n ${modified_json}"
return 0
}
requireProgram jq
_input=$(cat <<EOT
{
"MARC": "abc",
"PQR": "mno",
"XYZ": "stu"
}
EOT
)
# replaceJson --json "${_input}" --value Siva --key MARC
replaceJson --json "${_input}" --value Siva --key MARC --debug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment