From time to time there is requirement build JSON object at bash script. This can be done in several ways. Depend on complexity of requirement.
As first attemption came up to write exact JSON to variable, something like this
#!/usr/bin/env bash
JSON=$(cat <<-END
{
"what":"something",
"when":"now"
}
END
)
echo "$JSON"
As result this JSON is produced
{
"what": "something",
"when": "now"
}
Next attempt is add key values from variables with jq
help
#!/usr/bin/env bash
WHAT="something"
WHEN="now"
JSON=$(jq -n \
--arg what "$WHAT" \
--arg when "$WHEN" \
'$ARGS.named'
)
echo "$JSON"
Here is used jq
for JSON built.
--arg name value
passes values predefined variables. Value is available as $name.
All named arguments are also available as $ARGS.named
Because the format of $ARGS.named
is already an object, jq
can output it as is.
This is usable when JSON structure is fixed and known. But JSON can be variable, depend on usage. What if there some variable missing or next variable has to be added. Some more flexibility can be welcomed.
Here is approach how to create JSON progressively
#!/usr/bin/env bash
JSON=$(jq -n '')
WHAT="something"
if [[ -n "$WHAT" ]]; then
JSON=$(echo $JSON | jq --arg what "${WHAT}" '. += $ARGS.named')
fi
if [[ -n "$WHEN" ]]; then
JSON=$(echo $JSON | jq --arg when "${WHEN}" '. += $ARGS.named')
fi
echo "$JSON"
At beginning, with JSON=$(jq -n '')
empty JSON is created.
Then variables are assigned.
Next condition is crucial for JSON built.
if [[ -n "$WHAT" ]]; then
JSON=$(echo $JSON | jq --arg what "${WHAT}" '. += $ARGS.named')
fi
If variable is set and not null, will be added to JSON.
In this example $WHEN
variable was not assigned and was not added to final JSON.
With this technique, JSON creation in bash script can be so flexible.
Top comments (1)
thanks for the Post π