Skip to content

Instantly share code, notes, and snippets.

@GongT
Last active September 7, 2024 22:54
Show Gist options
  • Save GongT/96894ccb324b8cd814bac06bd51306d4 to your computer and use it in GitHub Desktop.
Save GongT/96894ccb324b8cd814bac06bd51306d4 to your computer and use it in GitHub Desktop.
protect bash array with json
function json_array() {
if [[ $# -eq 0 ]]; then
echo '[]'
fi
# --ascii-output if no base64
jq --null-input --compact-output --slurp '$ARGS.positional' --args "$@"
}
function json_array_get_back() {
local -i SIZE i
local VARNAME="$1" JSON="$2"
local -a ARR=()
SIZE=$(echo "$JSON" | jq --compact-output '.|length')
for ((i = 0; i < SIZE; i++)); do
ARR+=("$(echo "$JSON" | jq --compact-output --raw-output ".[$i]")")
done
eval "$VARNAME=(\"\${ARR[@]}\")"
}
STR=$'\x1Bfrom\tthe world'
BASH_ARR=(
printf
"say: %s! %s\n"
"$STR"
'🥺'
)
JSON=$(json_array "${BASH_ARR[@]}")
echo "json = $JSON" >&2
ENCODE=$(echo "$JSON" | base64 --wrap=0 -)
echo "encoded = $ENCODE" >&2
echo "$ENCODE"
declare -a NEW_ARR=()
json_array_get_back NEW_ARR "$(base64 -d)"
"${NEW_ARR[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment