Skip to content

Instantly share code, notes, and snippets.

@nicholaswmin
Last active July 19, 2024 16:18
Show Gist options
  • Save nicholaswmin/1375b8c4e931ecf3869d07f56e77a895 to your computer and use it in GitHub Desktop.
Save nicholaswmin/1375b8c4e931ecf3869d07f56e77a895 to your computer and use it in GitHub Desktop.
Bash shell function which removes a key from a JSON file
#!/usr/bin/env
#######################################
# deleteJSONKey() $key $json_file_path
#
# Deletes a property from a JSON file,
# taking care of dangling commas if needed
#
# Usage example:
#
# deleteJSONKey "version" package.json
#
# Removes the "version" property
# of file "package.json""
#
# Note:
# - Only the 1st match is removed.
# - To remove multiple instances of the same key,
# call it multiple times.
#
# Globals:
#
# - none
#
# Arguments:
#
# - key : the JSON key/property name to remove
# - file: the JSON file path
#
# Returns:
#
# - 0 if key was deleted
# - 1 otherwise
#
# License: MIT
# Authors: @nicholaswmin
#######################################
deleteJSONKey () {
local key=$1
local file=$2
# verify params
if ! [[ "${key}" ]]; then
echo "- Missing \"key\" parameter"
return 1
fi
if ! [[ "${file}" ]]; then
echo "- Missing \"file\" parameter"
return 1
fi
if [[ ! -f "${file}" ]]; then
echo "- File: $file does not exist"
return 1
fi
local count=$(grep -n "${key}" "${file}" | wc -l)
local line_num=$(grep -n "${key}" "${file}" | head -1 | grep -Eo '^[^:]+')
if [[ -z "$line_num" ]]; then
echo "- Cannot find key: \"${1}\" in: ${file}"
return 1
fi
# we also need the previous line in case it has
# a dangling comma
local line=$(sed -n "${line_num}"p "${file}")
local prev_line_num=$((line_num - 1))
local prev_line=$(sed -n "${prev_line_num}"p "${file}")
# remove dangling comma of previous line,
# if we need to.
if ! [[ "${line: -1}" =~ ^[,]$ ]]; then
if [[ -n "$prev_line" ]] && [[ "${prev_line: -1}" =~ ^[,]$ ]]; then
sed -i "" $prev_line_num's/,//g' ${file}
fi
fi
sed -i "" "${line_num}d" "${file}"
echo "removed: 1, line number: ${line_num}, remaining: $((--count))"
return 0
}
@nicholaswmin
Copy link
Author

nicholaswmin commented Jul 19, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment