Env-zu-JSON-Konverter
Konvertieren Sie .env-Dateien in JSON-Objekte für Tools und Automatisierung
What is .env to JSON Conversion?
Converting .env files to JSON transforms flat KEY=VALUE environment
configuration into a structured, machine-readable format suitable for automation pipelines, CI/CD
systems, container orchestration platforms, and programmatic access. Unlike formatting or beautifying
a .env file — which preserves the original dotenv syntax — conversion to JSON produces
a fundamentally different output: a standards-compliant JSON object where each environment variable
becomes a property with its key as the field name and its value as a JSON string.
This conversion bridges the gap between the simple dotenv format used in local development and the
structured configuration formats expected by modern infrastructure tools. Kubernetes ConfigMaps,
Docker secrets, AWS Systems Manager Parameter Store, HashiCorp Vault, and Terraform variable files
all consume JSON natively. By converting your .env into JSON, you can pipe configuration
directly into these systems without writing custom parsing logic, enabling a single source of truth
for environment variables across development, staging, and production environments.
Why Convert .env Files to JSON for Automation Pipelines
Automation pipelines — whether GitHub Actions, GitLab CI, Jenkins, or CircleCI — require
configuration in structured formats that can be validated, merged, and transformed programmatically.
While .env files work well for local development with tools like dotenv,
they lack the structure needed for pipeline automation:
-
No native schema validation: JSON supports schema validation via JSON Schema,
allowing CI pipelines to reject invalid configuration before deployment. A flat
.envfile has no mechanism to enforce types, required fields, or value constraints. -
No nested structure: Complex configurations often require nesting (database
credentials grouped under a
databasekey, API keys underservices). JSON supports arbitrary nesting while.envfiles are strictly flat key-value pairs. - No comments in JSON — by design: While this seems like a disadvantage, it means JSON configuration is purely data. Comments live in documentation, not in the configuration file itself, preventing configuration drift where comments become outdated and misleading.
-
Universal parsing: Every programming language includes a JSON parser in its
standard library. Parsing
.envfiles requires a third-party library (dotenv, godotenv, python-dotenv) with subtly different parsing rules across implementations. JSON parsing is deterministic and standardized by ECMA-404. -
API compatibility: REST APIs, webhook payloads, and service mesh configuration
endpoints expect JSON bodies. Converting
.envto JSON enables direct HTTP POST of configuration to services like Consul, Vault, or custom config management APIs.
Kubernetes ConfigMaps and Docker Secrets Integration
Container orchestration platforms consume configuration as JSON or YAML structures — not raw
dotenv files. Converting your .env to JSON is the first step toward creating
Kubernetes ConfigMaps, Docker Swarm secrets, and Helm chart values from a single configuration source.
-
Kubernetes ConfigMaps: A ConfigMap's
datafield accepts string key-value pairs. While you can embed an entire.envfile as a single key, converting to JSON and then to a proper ConfigMap YAML gives you granular control — individual environment variables become separate ConfigMap keys that can be mounted individually or referenced in pod specs withvalueFrom.configMapKeyRef. -
Docker secrets: Docker Swarm secrets and Docker Compose secrets accept files.
Converting sensitive
.enventries to JSON allows you to store structured secrets that applications parse with type safety, rather than relying on line-by-line dotenv parsing inside the container. -
Helm values: Helm chart
values.yamlfiles often define environment variable blocks as structured objects. Converting.envto JSON provides the intermediate representation needed to generate Helm values programmatically, ensuring that chart deployments match the developer's local.envconfiguration. -
GitOps workflows: ArgoCD, Flux, and other GitOps tools reconcile state from
Git repositories containing JSON or YAML manifests. Storing configuration as JSON (converted
from developer-friendly
.envfiles) enables GitOps reconciliation with schema validation at the PR stage.
CI/CD Pipeline Integration Patterns
Modern CI/CD systems provide native support for JSON configuration through environment variable
injection, secret management, and dynamic configuration generation. Converting .env
files to JSON unlocks several powerful pipeline patterns:
-
GitHub Actions: Use
fromJSON()in workflow expressions to dynamically set matrix strategies, conditional steps, or environment-specific deployments from a JSON configuration file generated from your.env. -
GitLab CI variables: GitLab's API accepts JSON payloads for bulk variable
creation. Converting your
.envto JSON enables scripted synchronization of project variables viacurlto the GitLab Variables API. -
AWS Parameter Store: AWS Systems Manager Parameter Store accepts JSON for
structured parameters. Converting
.envto JSON withaws ssm put-parameter --type String --value '{"DB_HOST":"..."}'stores all configuration as a single versioned parameter that applications retrieve at runtime. -
Terraform
tfvars.json: Terraform reads.auto.tfvars.jsonfiles automatically. Converting your application's.envto the JSONtfvarsformat lets you drive infrastructure provisioning from the same configuration that your application consumes locally.
Schema Validation and Type Safety for Environment Configuration
One of the strongest advantages of converting .env to JSON is the ability to apply
schema validation. Environment variables are inherently untyped strings — a missing variable or
a typo in a value causes runtime failures that are difficult to debug. JSON Schema enforcement
catches these errors at build time:
- Required fields: Define which variables must be present in every environment. Schema validation rejects deployments missing critical configuration like database connection strings or API keys before the application starts.
-
Type coercion: Validate that
PORTis a numeric string,ENABLE_CACHEis "true" or "false", andLOG_LEVELis one of "debug", "info", "warn", "error". JSON Schema'senumandpatternkeywords catch misconfiguration before deployment. - Environment parity: Define separate schemas for development, staging, and production. Production schemas can require SSL-related variables, monitoring endpoints, and disaster recovery configuration that are optional in development.
- Documentation as code: A JSON Schema serves as living documentation of your application's configuration surface. New team members can inspect the schema to understand what variables exist, their allowed values, and their purposes — without reading source code.
Code Examples
Converting .env to JSON with Node.js
const fs = require('fs');
const path = require('path');
function envToJson(envContent) {
const result = {};
const lines = envContent.split('\n');
for (const line of lines) {
const trimmed = line.trim();
// Skip empty lines and comments
if (!trimmed || trimmed.startsWith('#')) continue;
const equalsIndex = trimmed.indexOf('=');
if (equalsIndex === -1) continue;
const key = trimmed.substring(0, equalsIndex).trim();
let value = trimmed.substring(equalsIndex + 1).trim();
// Remove surrounding quotes if present
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
result[key] = value;
}
return result;
}
// Read .env file and convert to JSON
const envPath = path.resolve(process.cwd(), '.env');
const envContent = fs.readFileSync(envPath, 'utf-8');
const jsonConfig = envToJson(envContent);
// Write JSON output
fs.writeFileSync(
'config.json',
JSON.stringify(jsonConfig, null, 2)
);
console.log('Converted .env to JSON:', jsonConfig);Output:
{
"NODE_ENV": "production",
"DB_HOST": "db.example.com",
"DB_PORT": "5432",
"DB_NAME": "myapp",
"API_KEY": "sk-abc123def456",
"ENABLE_CACHE": "true"
}Using .env-derived JSON in a GitHub Actions Workflow
# .github/workflows/deploy.yml
name: Deploy with JSON Config
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Convert .env to JSON for deployment
run: |
node -e "
const fs = require('fs');
const env = fs.readFileSync('.env.production', 'utf-8');
const json = {};
env.split('\n').forEach(line => {
const [key, ...val] = line.split('=');
if (key && !key.startsWith('#'))
json[key.trim()] = val.join('=').trim();
});
fs.writeFileSync('deploy-config.json', JSON.stringify(json, null, 2));
"
- name: Validate config against schema
run: npx ajv validate -s config-schema.json -d deploy-config.json
- name: Push to AWS Parameter Store
run: |
aws ssm put-parameter \
--name "/myapp/production/config" \
--type "String" \
--value "$(cat deploy-config.json)" \
--overwriteGenerating a Kubernetes ConfigMap from Converted JSON
#!/bin/bash
# convert-env-to-configmap.sh
# Converts .env file to a Kubernetes ConfigMap manifest via JSON
ENV_FILE=".env.production"
CONFIGMAP_NAME="app-config"
NAMESPACE="default"
# Step 1: Convert .env to JSON
JSON_CONFIG=$(node -e "
const fs = require('fs');
const env = fs.readFileSync('$ENV_FILE', 'utf-8');
const config = {};
env.split('\n').forEach(line => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) return;
const idx = trimmed.indexOf('=');
if (idx === -1) return;
config[trimmed.substring(0, idx)] = trimmed.substring(idx + 1);
});
process.stdout.write(JSON.stringify(config));
")
# Step 2: Generate ConfigMap YAML from JSON keys
echo "apiVersion: v1"
echo "kind: ConfigMap"
echo "metadata:"
echo " name: $CONFIGMAP_NAME"
echo " namespace: $NAMESPACE"
echo "data:"
echo "$JSON_CONFIG" | node -e "
const input = require('fs').readFileSync('/dev/stdin', 'utf-8');
const config = JSON.parse(input);
Object.entries(config).forEach(([key, value]) => {
console.log(' ' + key + ': "' + value.replace(/"/g, '\\"') + '"');
});
"Output:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: default
data:
NODE_ENV: "production"
DB_HOST: "db.example.com"
DB_PORT: "5432"
API_KEY: "sk-abc123def456" Häufig Gestellte Fragen
What does the environment to JSON converter do?
It parses .env-style key-value pairs and turns them into a JSON object that is easier to inspect, pass around, or feed into other tools.
Are comments included in the JSON output?
No. Comments are ignored because JSON has no comment syntax and pretending otherwise is how you get broken automation.
What happens with duplicate variables?
The last value wins, and the converter reports a warning so you can clean up the source file if needed.
Does it support quoted values?
Yes. Quoted values are unwrapped and basic escape sequences are decoded before serialization.