Skip to content

Instantly share code, notes, and snippets.

@marshyon
Last active September 11, 2022 13:46
Show Gist options
  • Save marshyon/5b2550a6de222c2b42795d321896f5c6 to your computer and use it in GitHub Desktop.
Save marshyon/5b2550a6de222c2b42795d321896f5c6 to your computer and use it in GitHub Desktop.
bash write and read simple JSON configuration data
{ "service3455": "42", "service3045": "89", "service2345": "33" }
store_config() {
if [[ -z $1 ]] && [[ -z $2 ]] ; then
config_json_data=$(echo '{}' | jq '.')
else
config_json_data=$(echo $config_json_data | jq --arg v "$2" --arg k "$1" '.[$k] |= $v ')
fi
echo $config_json_data
}
lookup_config_value() {
echo $config_json_data | jq --arg v $1 '.[$v]'
}
write.sh
read.sh
raw data is : { "service3455": "42", "service3045": "89", "service2345": "33" }
key_1 value is 42
#!/usr/bin/env bash
# import common functions for reading
# and writing configuration
. my_funcs.sh
# read in configuration data from
# configuration data file
config_json_file="config.json"
config_json_data=$(cat $config_json_file)
# output data and a queried configuration
# value
echo "raw data is : "$config_json_data
key_1="service3455"
query=$(lookup_config_value $key_1 | sed "s/\"//g")
echo "key_1 value is ${query}"
#!/usr/bin/env bash
# import common functions for reading
# and writing configuration
. my_funcs.sh
# set up data to be saved
key_1="service3455"
key_2="service3045"
key_3="service2345"
value_to_be_saved=42
config_json_file="config.json"
# initialise config_json_data
config_json_data=$(store_config)
# store key value data
config_json_data=$(store_config $key_1 $value_to_be_saved)
config_json_data=$(store_config $key_2 89)
config_json_data=$(store_config $key_3 33)
# save config data to a file
echo $config_json_data > $config_json_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment