Skip to content

Instantly share code, notes, and snippets.

@thenets
Created September 25, 2021 18:08
Show Gist options
  • Save thenets/b845dda76d606d275656f9e12875ae8d to your computer and use it in GitHub Desktop.
Save thenets/b845dda76d606d275656f9e12875ae8d to your computer and use it in GitHub Desktop.
Bash functions for JSON editor
#!/bin/bash
# Required packages:
# - python3
# - jq
#
# Install packages:
# - sudo apt-get install python3 jq
set -e
function f_write_config() {
# Write JSON config file (./config.json)
#
# arg: $1 - key (string)
# arg: $2 - value (string | json)
local key="$1"
local value="$2"
# Validations
# check if config.json exist
if [ ! -f ./config.json ]; then
echo "config.json not found"
exit 1
fi
# check if config.json has valid json format
if ! jq -e . > /dev/null 2>&1 < ./config.json; then
echo "config.json has invalid json format"
exit 1
fi
# add quotes if value is alpha-numeric
# and encode $value to base64
if [[ "$value" =~ ^[0-9]+$ ]]; then
value_base64=$(echo -n \""$value\"" | base64)
else
value_base64=$(echo -n "$value" | base64)
fi
# Multiline adhoc run python code
local result=$(python3 << EOF
import json
import base64
# read config file or create if not exists
try:
with open('config.json', 'r') as f:
content = json.load(f)
except:
content = {}
# decode base64 value
value_decoded = base64.b64decode("$value_base64")
content.update({"$key": json.loads(value_decoded)})
json_content = json.dumps(content)
# save to file
with open("./config.json", "w") as f:
f.write(json_content)
EOF
)
}
function f_get_config() {
# Get JSON config file (./config.json)
# arg: $1 - key (string)
#
# return: $value (string | json)
local key="$1"
# Get key from config with jq
value=$(cat ./config.json | jq -r ".$key")
}
# How to use
# example
f_write_config aws_region "us-east-1"
f_write_config aws_credentials '{"access_key": "1234", "secret_key": "5678"}'
f_get_config aws_region
echo $value
cat ./config.json | jq .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment