Skip to content

Instantly share code, notes, and snippets.

@kr
Created August 6, 2013 00:59
Show Gist options
  • Save kr/6161118 to your computer and use it in GitHub Desktop.
Save kr/6161118 to your computer and use it in GitHub Desktop.
convert a json dictionary into environment variables
#!/usr/bin/env python
# jsonenv reads a json object as input and produces
# escaped shell commands for setting environment vars
import json
import pipes
import sys
for k, v in json.load(sys.stdin).items():
k = pipes.quote(k)
v = pipes.quote(v)
print "%s=%s export %s;" % (k, v, k)
@jakub-bochenski
Copy link

pipes.quote is wrong for the env names. Env names can only contain word characters, so it should be instead sth like k = re.sub("[^a-zA-Z_0-9]+", "_", k)

@cfraizer
Copy link

Have you tried jq as an alternative?

$ jq -r '. | to_entries[] | "export \(.key)=\(@sh "\(.value)")"' ~/tmp/x.json
export URL='https://foo:bar@example.com/'
export OTHER='foo " bar '\''baz'\'''

That's not identical output to the Python above, but it is equivalent. (To encode single-quote (&apos;) characters, it uses <backslash>&apos; outside quotes instead of &quot;&apos;&quot;.)

@brianjychan
Copy link

Thanks

@jankuc
Copy link

jankuc commented Mar 31, 2021

this should work without the need to paste code into cmdline again:

for k, v in json.load(open('local.settings.json')).items():
    os.environ[k] = v

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment