Created
January 4, 2026 08:18
-
-
Save OhadRubin/3c9ff8a106d7d854e178d158f9068b7b to your computer and use it in GitHub Desktop.
Bash function for JSON templating with environment variable substitution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| json_template_to_canon() { | |
| # stdin: template with ${VARS}; output: canonical (minified) json | |
| # Substitutes environment variables in a JSON template. | |
| # | |
| # NOTE: Variables MUST be exported (not just set) for this to work. | |
| # NOTE: Unset variables are left as-is (safe_substitute behavior). | |
| # | |
| # Example 1 - single line: | |
| # export PORT=8088 FLAGS="--foo=bar" | |
| # echo '{"port":"${PORT}","flags":"${FLAGS}"}' | json_template_to_canon | |
| # # Output: {"port":"8088","flags":"--foo=bar"} | |
| # | |
| # Example 2 - multiline with heredoc: | |
| # export PORT=8088 NAME="my-server" | |
| # cat << 'EOF' | json_template_to_canon | |
| # { | |
| # "server": { | |
| # "port": "${PORT}", | |
| # "name": "${NAME}" | |
| # }, | |
| # "enabled": true | |
| # } | |
| # EOF | |
| # # Output: {"server":{"port":"8088","name":"my-server"},"enabled":true} | |
| # | |
| # Example 3 - capture to variable: | |
| # export URL="http://localhost:8088" | |
| # payload="$(cat << 'EOF' | json_template_to_canon | |
| # {"base_url": "${URL}"} | |
| # EOF | |
| # )" | |
| # echo "$payload" | |
| # | |
| local input | |
| input="$(cat)" | |
| python3 - "$input" <<'PY' | |
| import os, sys, json | |
| from string import Template | |
| tmpl = Template(sys.argv[1]) | |
| rendered = tmpl.safe_substitute(os.environ) | |
| obj = json.loads(rendered) | |
| print(json.dumps(obj, separators=(",", ":"), ensure_ascii=False)) | |
| PY | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment