Skip to content

Instantly share code, notes, and snippets.

@whchi
Created December 16, 2025 09:09
Show Gist options
  • Select an option

  • Save whchi/0c59ec78aaeb15e86f2974d34833de95 to your computer and use it in GitHub Desktop.

Select an option

Save whchi/0c59ec78aaeb15e86f2974d34833de95 to your computer and use it in GitHub Desktop.
convert env file data to json
#!/usr/bin/env bash
# This script converts environment variables to a JSON object.
# Usage: ./env-to-json.sh [.env file path]
set -euo pipefail
ENV_FILE="${1:-.env}"
# Function to escape JSON strings
json_escape() {
local string="$1"
# Escape backslashes, quotes, and control characters
printf '%s' "$string" | \
sed 's/\\/\\\\/g' | \
sed 's/"/\\"/g' | \
sed 's/\t/\\t/g' | \
sed 's/\r/\\r/g' | \
sed 's/\n/\\n/g'
}
# Start JSON object
echo "{"
first=true
# Read .env file if it exists
if [[ -f "$ENV_FILE" ]]; then
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip empty lines and comments
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
# Parse KEY=VALUE format
if [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=[[:space:]]*(.*)[[:space:]]*$ ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
# Remove surrounding quotes if present
if [[ "$value" =~ ^\"(.*)\"$ ]] || [[ "$value" =~ ^\'(.*)\'$ ]]; then
value="${BASH_REMATCH[1]}"
fi
# Add comma separator if not first entry
if [[ "$first" == true ]]; then
first=false
else
echo ","
fi
# Output JSON key-value pair
# Handle special cases: null, boolean, and empty values
if [[ "$value" == "null" ]]; then
printf ' "%s": null' "$key"
elif [[ "$value" == "true" || "$value" == "false" ]]; then
printf ' "%s": %s' "$key" "$value"
elif [[ -z "$value" ]]; then
printf ' "%s": ""' "$key"
else
printf ' "%s": "%s"' "$key" "$(json_escape "$value")"
fi
fi
done < "$ENV_FILE"
else
echo " \"error\": \"File $ENV_FILE not found\"" >&2
fi
# Close JSON object
echo ""
echo "}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment