I'm building a bash script that needs to send a json payload to an API. The payload below is stored in payload.json
, will be used all the time and is in the same path as the script. The ""
values are what I need to populate with variables from within the same script.
{
"appId": "",
"appName": "",
"authType": "OIDC",
"authSettings": {
"applicationType": "SERVICE",
"clientAuthenticationType": "CLIENT_SECRET",
"grantTypes": [
"CLIENT_CREDENTIALS"
],
"groups": [
""
],
"responseTypes": [
"TOKEN"
],
"inclusion": [
"",
"",
"",
""
],
"tokenValidity": {
"accessTokenLifetimeMinutes": 60,
"refreshTokenLifetimeMinutes": 10080,
"refreshTokenWindowMinutes": 1440
}
}
}
I'm not sure how to achieve this correctly.
How can I pass single values to .appId
, .appName
and multiple values to .groups[]
, .inclusion[]
all at the same time?
I started on this path for each variable but got nowhere:
appId=31337
jq '.appId = "${appId}"' config.json > tempfile.json
Any help is appreciated.
CodePudding user response:
I'd use some "nested" jq calls:
appId=1234
appName="My App"
groups=(g1 g2 g3)
inclusion=(i1 i2 i3 i4 i5)
jq --arg appId "$appId"\
--arg appName "$appName" \
--argjson groups "$(jq -n --args '$ARGS.positional' "${groups[@]}")" \
--argjson inclusion "$(jq -n --args '$ARGS.positional' "${inclusion[@]}")" \
' .appId = $appId
| .appName = $appName
| .authSettings.groups = $groups
| .authSettings.inclusion = $inclusion
' template.json
If the appId should be a number in the resulting JSON, use --argjson
instead of --arg
CodePudding user response:
You can use --arg
and --argjson
with null input, e.g.
jq -n --arg id "$appid" --arg name "$appname" \
--argjson groups '["your", "groups", "here"]' \
'{
"appId": $id,
"appName": $name,
"authType": "OIDC",
"authSettings": {
"applicationType": "SERVICE",
"clientAuthenticationType": "CLIENT_SECRET",
"grantTypes": [
"CLIENT_CREDENTIALS"
],
"groups": $groups,
"responseTypes": [
"TOKEN"
],
"inclusion": [
"",
"",
"",
""
],
"tokenValidity": {
"accessTokenLifetimeMinutes": 60,
"refreshTokenLifetimeMinutes": 10080,
"refreshTokenWindowMinutes": 1440
}
}
}'
Or, if you cannot modify the template file to be a jq filter/program, you can load it and then merge it with your custom arguments. Note that you need to match the structure exactly for this to work:
jq --arg appId 123 --argjson groups '["your","groups"]' \
'. * { $appId, authSettings: { $groups } }' template.json
Alternatively by assigning each property:
jq --arg appId 123 --argjson groups '["your","groups"]' \
'.appId = $appId | .authSettings.groups = $groups' tpl.json