How the JSON to .env conversion works
A .env file is a flat list of KEY=value lines, while JSON can nest objects to any depth. The converter walks the object and builds one variable per leaf value. Each step down into an object adds the key and an underscore to the name.
- Flatten:
{"stripe": {"webhook": {"secret": "whsec_…"}}}becomes the pathstripe_webhook_secret. - Normalize the name: the path is uppercased and every character outside
A-Z,0-9and_turns into_, soallowed-originsbecomesALLOWED_ORIGINS. - Serialize the value: strings and numbers are written as they are,
nullbecomes an empty value, arrays become a JSON string. - Quote when needed: a value with whitespace,
#, a quote,$, a backslash or a line break is wrapped in double quotes, and inner double quotes are escaped.
Want the opposite direction? The ENV to JSON converter parses a .env back into an object and can turn "true" and "3000" back into real booleans and numbers.
What changes when JSON becomes a .env file
| JSON input | .env output | What your app receives |
|---|---|---|
"port": 3000 | PORT=3000 | the string "3000" |
"debug": true | DEBUG=true | the string "true" (truthy even when it says "false") |
"tags": ["a","b"] | TAGS="[\"a\",\"b\"]" | a JSON string, parse with JSON.parse |
"dsn": null | DSN= | an empty string, or undefined with some loaders |
"db": {"url": "…"} | DB_URL=… | one flat variable per leaf |
The safest pattern is to validate and cast once at startup, for example with zod in Node.js or pydantic-settings in Python, instead of calling Number() all over the codebase. The .env validator catches malformed lines before your app does.
Converting JSON to .env on the command line
For a flat JSON object without nesting, jq does the job in CI pipelines:
# flat object only: {"PORT": 3000, "NODE_ENV": "production"}
jq -r 'to_entries[] | "\(.key)=\(.value)"' config.json > .env
# AWS Secrets Manager (SecretString is a JSON object)
aws secretsmanager get-secret-value --secret-id prod/app \
--query SecretString --output text \
| jq -r 'to_entries[] | "\(.key)=\(.value)"' > .envThese one-liners do not flatten nested objects and do not quote values containing # or spaces. For anything nested or containing passwords, paste it into the converter above, then run the result through the .env formatter if you want aligned, sorted output.