DEV Community

Cover image for Stop Wrestling with Environment Variables: How to Convert JSON to .env Files Instantly
Goodnews
Goodnews

Posted on

Stop Wrestling with Environment Variables: How to Convert JSON to .env Files Instantly

The Environment Variable Headache Every Developer Knows

You've been there: you have a perfectly good JSON configuration file, but your deployment pipeline needs a .env file. Or your Docker container expects environment variables. Or your CI/CD tool only reads dotenv format.

So what do you do? Manually copy-paste each key-value pair? Write a custom script for the hundredth time? Waste 30 minutes reformatting configuration that should take 30 seconds?

There's a better way.

Introducing JSON-to-Env: Your Configuration Format Converter

@sourcepride/json-to-env is a lightweight Node.js library that transforms JSON objects into dotenv-style environment variables instantly. No manual formatting, no custom scripts, just clean conversion.

Real-World DevOps Pain Points This Solves

1. Docker and Container Deployments

You're running microservices in Docker. Your developers love working with JSON config files during development, but Docker Compose and Kubernetes prefer environment variables.

Before:

# Manually translating config.json to .env
# Error-prone, time-consuming, soul-crushing
Enter fullscreen mode Exit fullscreen mode

After:

npx json-to-env ./config.json ./.env
# Done in seconds
Enter fullscreen mode Exit fullscreen mode

2. CI/CD Pipeline Configuration

GitHub Actions, GitLab CI, CircleCI—they all consume environment variables. You have configuration stored in JSON (maybe from AWS Parameter Store, Azure Key Vault, or your config management system), but need to feed it into your pipeline.

import { jsonToEnv } from "@sourcepride/json-to-env";

// Fetch config from your secret manager
const config = await fetchFromVault();

// Convert to env format instantly
const envVars = jsonToEnv(config);
Enter fullscreen mode Exit fullscreen mode

3. Multi-Environment Management

You maintain separate JSON files for dev, staging, and production. Now you need corresponding .env files for tools that don't read JSON.

# Convert all environments at once
json-to-env ./config.dev.json ./.env.dev
json-to-env ./config.staging.json ./.env.staging
json-to-env ./config.prod.json ./.env.production
Enter fullscreen mode Exit fullscreen mode

4. Legacy System Integration

Your shiny new microservice speaks JSON, but the legacy deployment system from 2015 only understands .env files. Bridge the gap without maintaining duplicate configuration.

5. Serverless and Cloud Functions

AWS Lambda, Google Cloud Functions, Azure Functions—they all accept environment variables. Convert your JSON config once during deployment:

// In your deployment script
const envConfig = jsonToEnv(serverlessConfig);
// Upload to your cloud provider
Enter fullscreen mode Exit fullscreen mode

Key Features That Save Time

Handle Complex Nested Objects

jsonToEnv({
  database: {
    host: "localhost",
    port: 5432,
    credentials: {
      username: "admin",
      password: "secret"
    }
  }
});

// Outputs:
// DATABASE_HOST=localhost
// DATABASE_PORT=5432
// DATABASE_CREDENTIALS_USERNAME=admin
// DATABASE_CREDENTIALS_PASSWORD=secret
Enter fullscreen mode Exit fullscreen mode

Work with Arrays Intelligently

jsonToEnv(
  {
    servers: [
      { host: "server1.com", port: 8080 },
      { host: "server2.com", port: 8081 }
    ]
  },
  { arrays: "indexed" }
);

// Outputs:
// SERVERS_0_HOST=server1.com
// SERVERS_0_PORT=8080
// SERVERS_1_HOST=server2.com
// SERVERS_1_PORT=8081
Enter fullscreen mode Exit fullscreen mode

Flexible Input Formats

Works with strict JSON, JavaScript object literals (JSON5), or plain JavaScript objects. No need to worry about trailing commas or quote styles.

Quick Installation and Usage

npm install @sourcepride/json-to-env
Enter fullscreen mode Exit fullscreen mode

CLI (no code required):

npx json-to-env ./config.json ./.env
Enter fullscreen mode Exit fullscreen mode

In your code:

import { jsonToEnv } from "@sourcepride/json-to-env";

const envContent = jsonToEnv({
  API_KEY: "your-key",
  PORT: 3000,
  DEBUG: true
});

// API_KEY=your-key
// PORT=3000
// DEBUG=true
Enter fullscreen mode Exit fullscreen mode

Common Use Cases in DevOps Workflows

Kubernetes ConfigMaps to Environment Variables

# Extract JSON from ConfigMap, convert to .env
kubectl get configmap my-config -o json | \
  jq '.data' | \
  npx json-to-env > .env
Enter fullscreen mode Exit fullscreen mode

Terraform Outputs to .env

# Convert Terraform outputs to environment variables
terraform output -json | npx json-to-env > infrastructure.env
Enter fullscreen mode Exit fullscreen mode

Secret Manager Integration

// AWS Secrets Manager example
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
import { jsonToEnv } from "@sourcepride/json-to-env";

const secret = await client.send(new GetSecretValueCommand({ SecretId: "prod/api" }));
const config = JSON.parse(secret.SecretString);

// Convert to .env for local development
fs.writeFileSync('.env', jsonToEnv(config));
Enter fullscreen mode Exit fullscreen mode

Advanced Configuration Options

Custom naming conventions:

jsonToEnv(config, { keyCase: "lower_snake" }); // my_api_key
jsonToEnv(config, { keyCase: "camel_case" });  // myApiKey
Enter fullscreen mode Exit fullscreen mode

Add prefixes for namespacing:

jsonToEnv(config, { prefix: "APP" });
// APP_PORT=3000
// APP_HOST=localhost
Enter fullscreen mode Exit fullscreen mode

Control how nested objects are handled:

// Store entire object as JSON string in one variable
jsonToEnv({ metadata: { a: 1, b: 2 } }, { objects: "json" });
// METADATA={"a":1,"b":2}
Enter fullscreen mode Exit fullscreen mode

Why This Matters for DevOps Teams

  1. Consistency: One source of truth (JSON), multiple consumption formats
  2. Automation: Integrate into CI/CD pipelines without custom scripts
  3. Error Reduction: Eliminate manual transcription mistakes
  4. Time Savings: Convert configurations in seconds, not minutes
  5. Flexibility: Support both TypeScript/JavaScript and CLI workflows

Get Started in 60 Seconds

# Install globally
npm install -g @sourcepride/json-to-env

# Convert any JSON file
json-to-env my-config.json .env

# Or use without installing
npx @sourcepride/json-to-env config.json
Enter fullscreen mode Exit fullscreen mode

Conclusion

Stop wasting time manually converting configuration formats. Whether you're deploying Docker containers, managing multi-environment setups, or integrating with legacy systems, @sourcepride/json-to-env streamlines your workflow and eliminates configuration headaches.

Try it today and reclaim the time you've been losing to configuration busy work.

Resources:


Keywords: JSON to env converter, dotenv generator, environment variables from JSON, DevOps configuration management, Docker environment variables, Kubernetes config, CI/CD configuration, JSON5 to dotenv, configuration format conversion

Top comments (0)