Issue
I have a config file located in ~/.config/server_config.json
this json file contains the following info:
{
"server_name": "server1",
"mongodb_url":"mongodb://user:[email protected]:27017/dbname"
"other stuff": "stuff2"
}
I have a bash script that i use in a cronjob that will perform a mongodump daily, monthly, weekly, and do auto rotate backups, gzip, etc.
I want to be able to check this config file for the existence of the mongodb_url.
if exists, use that url that contains the username and password to pass into the mongodump script.
if the mongodb url does not exist in the json file, run the mongodump command normally using localhost with no authentication.
here is a snippet from the backup script
else # daily
echo "Starting critical tables daily backup $(date)" >> $LOG_LOCATION
for DATABASE in ${FULL_BACKUPS_ONLY_LIST//,/ }
do
for TABLE in ${CRITICAL_TABLES_LIST//,/ }
do
echo "backing up $DATABASE $TABLE ..."
mongodump -d $DATABASE -c $TABLE --out $FINAL_BACKUP_DIR
done
done
fi
I basically want to be able to parse this json file to use the right mongodb url with username and password included.
im thinking about using python to first parse the json file, then send the url as an input argument into the bash script since parsing json with bash seems very difficult. Unless there is some sed/awk magic that can happen.
Solution
You can use jq
bash command to parse the JSON file.
Sample test.json
File Contents:
{
"a": 1,
"b": 2,
"c": 4
}
bash command: jq '.b' test.json
Output: 2
Answered By - Bhima Rao Gogineni Answer Checked By - Willingham (WPSolving Volunteer)