Output UNIX environment as JSON

I need a single-line unix file that displays the current runtime as a JSON structure, for example: {"env-var": "env-value", ... etc.}}

This kind of work:

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

but it has some extra lines, and I think this will not work if the values ​​or environment variables have '=' characters or new lines in them.

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

+7
json environment-variables jq
source share
2 answers

Using jq 1.5 (e.g. jq 1.5rc2 - see http://stedolan.imtqy.com/jq ):

 $ jq -n env 
+9
source share

This works for me:

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

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

Adding parentheses around the print statement allows you to work in both Python 2 and 3D, so it should work for the foreseeable future on most * nix systems (especially since Python is used by default for any main distribution).

+7
source share

All Articles