Skip to content

Instantly share code, notes, and snippets.

@crashGoBoom
Created May 9, 2019 13:04
Show Gist options
  • Save crashGoBoom/cb708d14d3faeff37b98d0362449c086 to your computer and use it in GitHub Desktop.
Save crashGoBoom/cb708d14d3faeff37b98d0362449c086 to your computer and use it in GitHub Desktop.
Simple handy jq functions.
declare -r SOME_JSON_FILE="/path/to/json/file.json"
# Read a key from a file.
# Usage: _key_value=$(_read_json_key "key")
function _read_json_key() {
local -r _key="${1}"
jq --arg key "${_key}" -r '.[$key]' "${SOME_JSON_FILE}"
}
# Writes a json key into an existing file without overwriting.
# Usage: _write_json_key "key" "value"
function _write_json_key() {
local -r _key="${1}"
local -r _val="${2}"
local -r _temp="/tmp/.tmpfile.json"
echo "Writing ${_key}:${_val} to json file..."
jq \
--arg key "${_key}" \
--arg val "${_val}" \
'.[$key] = $val' "${SOME_JSON_FILE}" > "${_temp}"
mv -v "${_temp}" "${SOME_JSON_FILE}"
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment