Export JSON to environment variables in BASH
Phil Hadviger
Principal Site Reliability Engineer @ GLGI need these key/value pairs from JSON exported to the environment
There have been a few times where I've needed to take the contents of a JSON object and export them to the environment. While there are surely lots of way to do this with awk
, sed
and/or jq
in combination, I've opted to just create a bash function for it.
An input file called config.json
Just a file with two key/value pairs, which will be used in the example below.
The JQ syntax used in the function
Here we change the key/value object, into an array of consistent looking objects we can loop over.
By looping over each consistent object, we create an array with strings of key/value pairs.
We now only extract the strings from within the array.
Throwing this all into a bash function
The reason this has to be a function vs. a script, is because in order for the enviroment variables to persist in the active shell after the script terminates.
The while; do ... done
loops over each row returned from the jq
command, which is piped into the loop using Process Substitution. It then exports each key value pair.
--from-file
also uses Process Subsitution, in order to pretend it's pulling data from a JQ filter file.
The result of invoking the function with a file