feat(new tool): JSON to .env converter (#349)

Converts a flat JSON object into a .env file. Keys are upper-cased,
values are safely quoted when they contain whitespace, quotes, or env
special characters (#, $, `, \). Nested objects and arrays are
JSON-stringified and always quoted; null/undefined become "".

Follows the existing FormatTransformer pattern used by the other
json-to-* converters, including i18n via useI18n and the built-in
.env download button.

Co-authored-by: ShareVB <sharevb@gmail.com>
This commit is contained in:
hakimilgandShareVB authored and GitHub committed 2026-05-03 19:21:46 +02:00
1 parent f7f82a57d6
commit b05e70d6d8
6 files changed
+227

No files matched your search

+8
View File
@@ -551,6 +551,14 @@ tools:
input-label-your-json: Your JSON
input-placeholder-paste-your-json-here: Paste your JSON here...
output-label-yaml-from-your-json: YAML from your JSON
json-to-env:
title: JSON to .env
description: Convert a flat JSON object into a .env file. Keys are upper-cased and values are safely quoted when they contain whitespace, quotes, or env-special characters.
texts:
message-provided-json-is-not-a-valid-flat-object: Provided JSON is not a valid flat object.
input-label-your-json: Your JSON
input-placeholder-paste-your-json-here: Paste your JSON here...
output-label-env-from-your-json: .env from your JSON
json-to-javascript:
title: JSON to JS converter
description: Simply convert JSON to Javascript object with this live online converter.
+15
View File
@@ -0,0 +1,15 @@
import { Braces } from '@vicons/tabler';
import { defineTool } from '../tool';
import { translate as t } from '@/plugins/i18n.plugin';
export const tool = defineTool({
name: t('tools.json-to-env.title'),
path: '/json-to-env',
description: t('tools.json-to-env.description'),
keywords: ['json', 'to', 'env', 'dotenv', 'convert', 'environment', 'variables'],
component: () => import('./json-to-env.vue'),
icon: Braces,
createdAt: new Date('2026-04-17'),
npmPackages: ['json5'],
category: 'JSON',
});
@@ -0,0 +1,27 @@
import { expect, test } from '@playwright/test';
test.describe('Tool - JSON to .env', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/json-to-env');
});
test('Has correct title', async ({ page }) => {
await expect(page).toHaveTitle('JSON to .env - IT Tools');
});
test('Provided JSON is converted to .env', async ({ page }) => {
await page.getByTestId('input').fill(`{
"ACCESS_KEY": "mySecretAccessKey",
"AMQP_DNS": "amqp://a:b@rabbit/po",
"APP_ENV": "prod"
}`);
const generated = await page.getByTestId('area-content').innerText();
expect(generated.trim()).toEqual(
`ACCESS_KEY=mySecretAccessKey
AMQP_DNS=amqp://a:b@rabbit/po
APP_ENV=prod`.trim(),
);
});
});
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest';
import { convertJsonToEnv } from './json-to-env.service';
describe('json-to-env service', () => {
describe('convertJsonToEnv', () => {
it('converts a flat JSON object to .env lines', () => {
const json = JSON.stringify({
ACCESS_KEY: 'mySecretAccessKey',
APP_ENV: 'prod',
});
expect(convertJsonToEnv({ json })).toMatchInlineSnapshot(`
"ACCESS_KEY=mySecretAccessKey
APP_ENV=prod"
`);
});
it('uppercases keys by default', () => {
expect(convertJsonToEnv({ json: '{"app_env": "prod"}' })).toBe('APP_ENV=prod');
});
it('keeps original case when uppercaseKeys is false', () => {
expect(convertJsonToEnv({ json: '{"appEnv": "prod"}', uppercaseKeys: false })).toBe('appEnv=prod');
});
it('quotes values that contain spaces', () => {
expect(convertJsonToEnv({ json: '{"greeting": "hello world"}' })).toBe('GREETING="hello world"');
});
it('quotes values that contain double quotes and escapes them', () => {
expect(convertJsonToEnv({ json: '{"q": "he said \\"hi\\""}' })).toBe('Q="he said \\"hi\\""');
});
it('quotes values that contain # so they are not read as comments', () => {
expect(convertJsonToEnv({ json: '{"color": "#ff0000"}' })).toBe('COLOR="#ff0000"');
});
it('quotes empty string values', () => {
expect(convertJsonToEnv({ json: '{"empty": ""}' })).toBe('EMPTY=""');
});
it('converts null and undefined to empty values', () => {
expect(convertJsonToEnv({ json: '{"a": null}' })).toBe('A=""');
});
it('stringifies numbers and booleans', () => {
expect(convertJsonToEnv({ json: '{"port": 8080, "debug": true}' })).toMatchInlineSnapshot(`
"PORT=8080
DEBUG=true"
`);
});
it('serializes nested objects and arrays as JSON strings', () => {
const result = convertJsonToEnv({ json: '{"list": [1, 2, 3], "obj": {"a": 1}}' });
expect(result).toMatchInlineSnapshot(`
"LIST=\\"[1,2,3]\\"
OBJ=\\"{\\\\\\"a\\\\\\":1}\\""
`);
});
it('escapes newlines in values', () => {
expect(convertJsonToEnv({ json: '{"multi": "line1\\nline2"}' })).toBe('MULTI="line1\\nline2"');
});
it('returns empty string on empty input', () => {
expect(convertJsonToEnv({ json: '' })).toBe('');
expect(convertJsonToEnv({ json: ' ' })).toBe('');
});
it('throws when JSON is an array', () => {
expect(() => convertJsonToEnv({ json: '[1, 2, 3]' })).toThrow();
});
it('throws when JSON is a primitive', () => {
expect(() => convertJsonToEnv({ json: '"just a string"' })).toThrow();
});
it('throws on invalid JSON', () => {
expect(() => convertJsonToEnv({ json: '{not json}' })).toThrow();
});
});
});
@@ -0,0 +1,49 @@
import JSON5 from 'json5';
export { convertJsonToEnv };
function serializeValue(value: unknown): { value: string; forceQuote: boolean } {
if (value === null || value === undefined) {
return { value: '', forceQuote: true };
}
if (typeof value === 'object') {
return { value: JSON.stringify(value), forceQuote: true };
}
return { value: String(value), forceQuote: false };
}
function formatEnvValue({ value, forceQuote }: { value: string; forceQuote: boolean }): string {
const needsQuoting = forceQuote || value === '' || /[\s"'#`$\\]/.test(value);
if (!needsQuoting) {
return value;
}
const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
return `"${escaped}"`;
}
function convertJsonToEnv({ json, uppercaseKeys = true }: { json: string; uppercaseKeys?: boolean }): string {
const trimmed = json.trim();
if (trimmed === '') {
return '';
}
const parsed = JSON5.parse(trimmed);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new TypeError('JSON must be an object, not an array or primitive.');
}
return Object.entries(parsed)
.map(([key, value]) => {
const envKey = uppercaseKeys ? key.toUpperCase() : key;
const envValue = formatEnvValue(serializeValue(value));
return `${envKey}=${envValue}`;
})
.join('\n');
}
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import JSON5 from 'json5';
import { convertJsonToEnv } from './json-to-env.service';
import type { UseValidationRule } from '@/composable/validation';
import { withDefaultOnError } from '@/utils/defaults';
const { t } = useI18n();
const defaultValue = '{\n "ACCESS_KEY": "mySecretAccessKey",\n "AMQP_DNS": "amqp://a:b@rabbit/po",\n "APP_ENV": "prod"\n}';
function transformer(value: string) {
return withDefaultOnError(() => {
if (value === '') {
return '';
}
return convertJsonToEnv({ json: value });
}, '');
}
const rules: UseValidationRule<string>[] = [
{
validator: (v: string) => {
if (v === '') {
return true;
}
const parsed = JSON5.parse(v);
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed);
},
message: t('tools.json-to-env.texts.message-provided-json-is-not-a-valid-flat-object'),
},
];
</script>
<template>
<format-transformer
:input-label="t('tools.json-to-env.texts.input-label-your-json')"
:input-default="defaultValue"
:input-placeholder="t('tools.json-to-env.texts.input-placeholder-paste-your-json-here')"
:output-label="t('tools.json-to-env.texts.output-label-env-from-your-json')"
output-language="bash"
:input-validation-rules="rules"
:transformer="transformer"
download-file-name=".env"
/>
</template>