Construct Json (with ENV variables in BASH)
TLDR simplest string friendly example
jq --null-input --compact-output 'env | {
name: .ENV_VARIABLE_IN_YOUR_ENVIRONMENT,
tags: ["developer", "linux"]
}'
Construct JSON from environment variables
export NAME="John Doe"
export AGE=30
export ACTIVE=true
jq --null-input --compact-output 'env | {
name: .NAME,
age: (.AGE | tonumber),
active: (.ACTIVE | test("true"; "i")),
tags: ["developer", "linux"]
}'
{"name":"John Doe","age":30,"active":true,"tags":["developer","linux"]}
To use local or un-exported values use args
main() {
local name="John Doe"
local age=30
jq -nc \
--arg name "$name" \
--argjson age "$age" \
'{name: $name, age: $age}'
}
main
{"name":"John Doe","age":30}
Side note
You can construct inline JSON manually
main() {
local debug_mode=true
local port=8080
local active=false
local name="John Doe"
local value=null
CONFIG="{
\"debug\": $debug_mode,
\"port\": $port,
\"active\": $active,
\"name\": \"$name\",
\"value\": $value
}"
echo "$CONFIG"
}
main