Home > front end >  How can I convert JSON to an environment variable file format? [duplicate]
How can I convert JSON to an environment variable file format? [duplicate]

Time:09-17

I am fetching a AWS Parameter Store JSON response using the AWS cli:

echo $(aws ssm get-parameters-by-path --with-decryption --region eu-central-1 \
  --path "${PARAMETER_STORE_PREFIX}") >/home/ubuntu/.env.json

This outputs something like:

{
  "Parameters": [
    {
      "Name": "/EXAMPLE/CORS_ORIGIN",
      "Value": "https://example.com"
    },
    {
      "Name": "/EXAMPLE/DATABASE_URL",
      "Value": "db://user:pass@host:3306/example"
    }
  ]
}

Instead of writing to a JSON file, I'd like to write to a .env file instead with the following format:

CORS_ORIGIN="https://example.com"
DATABASE_URL="db://user:pass@host:3306/example"

How could I achieve this? I found similar questions like Exporting JSON to environment variables, but they do not deal with nested JSON / arrays

CodePudding user response:

Easy with jq and some string interpolation and @sh to properly quote the Value strings for shells:

$  jq -r '.Parameters[] | "\(.Name | .[rindex("/") 1:])=\(.Value | @sh)"' input.json
CORS_ORIGIN='https://example.com'
DATABASE_URL='db://user:pass@host:3306/example'
  • Related