0
votes

.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?

1
There are various libs that parse .env, such as this one which can return an Object representationAlan Friedman
Your mean is change env.json to .env ?hong4rc
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
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

1 Answers

3
votes

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