Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output UNIX environment as JSON

I'd like a unix one-liner that will output the current execution environment as a JSON structure like: { "env-var" : "env-value", ... etc ... }

This kinda works:

(echo "{"; printenv | sed 's/\"/\\\"/g' | sed -n 's|\(.*\)=\(.*\)|"\1"="\2"|p' | grep -v '^$' | paste -s -d"," -; echo "}")

but has some extra lines and I think won't work if the environment values or variables have '=' or newlines in them.

Would prefer pure bash/sh, but compact python / perl / ruby / etc one-liners would also be appreciated.

like image 215
Constance Eustace Avatar asked Aug 12 '15 22:08

Constance Eustace


People also ask

Can you use environment variables in JSON?

You have to wrap the environment variable of choice into another set of quotes in order for it to be valid JSON.

How do I export an environment variable?

To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.

What is ENV JSON?

The env. json file is a project-specific list of accessible variables. This file is the ideal place to store secret keys, project-wide properties, or anything else you want to obfuscate or share between your files.

What is the .ENV file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.


2 Answers

Using jq 1.5 (e.g. jq 1.5rc2 -- see http://stedolan.github.io/jq):

$ jq -n env
like image 85
peak Avatar answered Nov 21 '22 00:11

peak


This works for me:

python -c 'import json, os;print(json.dumps(dict(os.environ)))'

It's pretty simple; the main complication is that os.environ is a dict-like object, but it is not actually a dict, so you have to convert it to a dict before you feed it to the json serializer.

Adding parentheses around the print statement lets it work in both Python 2 and 3, so it should work for the forseeable future on most *nix systems (especially since Python comes by default on any major distro).

like image 26
Patrick Maupin Avatar answered Nov 20 '22 23:11

Patrick Maupin