Skip to content

Instantly share code, notes, and snippets.

@datfinesoul
Last active November 24, 2022 07:02
Show Gist options
  • Save datfinesoul/4eec7c53827e3eced31b48271cb520f3 to your computer and use it in GitHub Desktop.
Save datfinesoul/4eec7c53827e3eced31b48271cb520f3 to your computer and use it in GitHub Desktop.
Use `jq` to take a JSON object and export it as environment variables

There is extra code in here, but the key takeaway is:

  1. Use jq to convert an object with key/value pairs, into a key=value string list
  2. Feed that listinto a while loop, which then exports the environment variables

While this is done in a script, it needs to live in a function, if the environment variables are supposed to persist in the current shell.

#!/usr/bin/env bash
env | grep "YY\_" || echo "not found"
# open file descriptor 3 for reading from the following command
# pass null to jq and generate a sample json object
exec 3< <(jq -n '{ "YY_NAME": "test thi!", "YY_PATH": "/tmp/foo"}')
while IFS=$'\t\n' read -r LINE; do
export "${LINE}"
done < <(
<&3 jq -crM --from-file <(cat <<- DOC
# convert the object to an array of key/value pairs
# [{"key":"MY_NAME","value":"test"},{"key":"MY_PATH","value":"/tmp/foo"}]
to_entries
# convert each key/value pair into a string key=\"value\"
# ["MY_NAME=\"test\"","MY_PATH=\"/tmp/foo\""]
| map("\(.key)=\(.value)")
# extract each item from the array
| .[]
DOC
))
# close the file descriptor
exec 3<&-
env | grep "YY\_" && echo "found"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment