0

.env files are used to store environment variables in a certain project. I am looking to be able to easily programmatically modify an .env file, and in that case using JSON (a .json file) would be much easier as far as I can tell.

Say I had file like so env.json:

{
  "use_shell_version": true,
  "verbosityLevel":3,
  "color": "yellow"
}

is there a good way to export those? Is there some .env file format that is easily modified by machines instead of by hand?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • There are various libs that parse `.env`, such as this one which can [return an Object representation](https://github.com/motdotla/dotenv#config) – Alan Friedman Jul 12 '18 at 22:07
  • Your mean is change env.json to .env ? – hong4rc Jul 12 '18 at 23:04
  • Could you please elaborate the purpose of actually making a .env file out of a .json file ? I still cannot understand why would you like to do so, or what compels you to do so ? – nerdier.js Jul 12 '18 at 23:23
  • I'm looking for such a solution, too. In my case, I have a JSON file that's used as a key for an API, and I want to save it as as `.env` variable. I know how to do it, I'm just looking for a tool that does it. – Gal Grünfeld Jun 12 '19 at 10:52

1 Answers1

5

You can convert a JSON file to .env with a simple for loop.

function convertToEnv (object) {
    let envFile = ''
    for (const key of Object.keys(object)) {
        envFile += `${key}=${object[key]}\n`
    }
    return envFile
}

So the with your example object given,

const object = {
  "use_shell_version": true,
  "verbosityLevel":3,
  "color": "yellow"
}

const env = convertToEnv(object)

console.log(env)

output would be

use_shell_version=true 
verbosityLevel=3 
color=yellow
mvltshn
  • 245
  • 3
  • 10