diff --git a/locales/en.yml b/locales/en.yml index d267da0f..44d9751a 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -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. diff --git a/src/tools/json-to-env/index.ts b/src/tools/json-to-env/index.ts new file mode 100644 index 00000000..99a46c69 --- /dev/null +++ b/src/tools/json-to-env/index.ts @@ -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', +}); diff --git a/src/tools/json-to-env/json-to-env.e2e.spec.ts b/src/tools/json-to-env/json-to-env.e2e.spec.ts new file mode 100644 index 00000000..6cd56eb1 --- /dev/null +++ b/src/tools/json-to-env/json-to-env.e2e.spec.ts @@ -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(), + ); + }); +}); diff --git a/src/tools/json-to-env/json-to-env.service.test.ts b/src/tools/json-to-env/json-to-env.service.test.ts new file mode 100644 index 00000000..2d187f44 --- /dev/null +++ b/src/tools/json-to-env/json-to-env.service.test.ts @@ -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(); + }); + }); +}); diff --git a/src/tools/json-to-env/json-to-env.service.ts b/src/tools/json-to-env/json-to-env.service.ts new file mode 100644 index 00000000..e22a3e46 --- /dev/null +++ b/src/tools/json-to-env/json-to-env.service.ts @@ -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'); +} diff --git a/src/tools/json-to-env/json-to-env.vue b/src/tools/json-to-env/json-to-env.vue new file mode 100644 index 00000000..5168add6 --- /dev/null +++ b/src/tools/json-to-env/json-to-env.vue @@ -0,0 +1,46 @@ + + +