Last active
March 11, 2022 04:21
-
-
Save nexus166/62d6c71e2ded8c593a58756600b1ae93 to your computer and use it in GitHub Desktop.
convert bash arrays to json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
dict2json() { | |
local _data="" | |
trap 'if [[ -n "${_data}" ]]; then printf "{%s}" "${_data%?}" | jq -arc .; fi' RETURN | |
case "${#@}" in | |
0) | |
return | |
;; | |
1) | |
local _copy_decl="$(declare -p "${1}" 2>/dev/null)" | |
case "${_copy_decl}" in | |
"declare -a"*" ${1}="*) | |
_copy_decl="$(sed "s/^declare -a.* ${1}=//" <<<"${_copy_decl}")" | |
if ! eval "local -a _dict=${_copy_decl}"; then return 2; fi | |
for key in "${!_dict[@]}"; do | |
_data+="$(printf '"%s": %s,' "${key}" "$(printf '%s' "${_dict["${key}"]}" | jq -aMRs .)")" | |
done | |
;; | |
"declare -A"*" ${1}="*) | |
_copy_decl="$(sed "s/^declare -A.* ${1}=//" <<<"${_copy_decl}")" | |
if ! eval "local -A _dict=${_copy_decl}"; then return 2; fi | |
for key in "${!_dict[@]}"; do | |
_data+="$(printf '"%s": %s,' "${key}" "$(printf '%s' "${_dict["${key}"]}" | jq -aMRs .)")" | |
done | |
;; | |
*) | |
return 127 | |
;; | |
esac | |
;; | |
*) | |
local -a _arg_dict=("${@}") | |
for _i in $(seq 1 "${#@}"); do | |
if [[ $((_i % 2)) -eq 0 ]]; then | |
continue | |
fi | |
local _key="${_arg_dict["$((_i - 1))"]}" | |
local _val="${_arg_dict["${_i}"]}" | |
_data+="$(printf '"%s": %s,' "${_key}" "$(printf '%s' "${_val}" | jq -aMRs .)")" | |
done | |
;; | |
esac | |
} | |
declare -fx dict2json | |
if [[ ${#@} -gt 0 ]]; then | |
dict2json "${@}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment