Skip to content

Instantly share code, notes, and snippets.

@pogilvie
Last active May 8, 2021 16:27
Show Gist options
  • Save pogilvie/526a261121a9cb8a01e65a0fe02a90a3 to your computer and use it in GitHub Desktop.
Save pogilvie/526a261121a9cb8a01e65a0fe02a90a3 to your computer and use it in GitHub Desktop.
Exporting a JSON configuration file to SHELL environment variable

Source https://stackoverflow.com/questions/25378013/how-to-convert-a-json-object-to-key-value-format-in-jq

Given:

{
  "demo_name": "Jane Doe",
  "demo_id": "339e42a6-045a-47b5-98a4-310dd53d1053",
  "demo_phone": "555-123-4567"
}

Shell function json2env

json2env() {
   for v in $(jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' $1)
   do 
       export $v
   done
}

Source function and run ...

-> json2env doe.json
-> env|grep demo
demo_name=Jane
demo_phone=555-123-4567
demo_id=339e42a6-045a-47b5-98a4-310dd53d1053
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment