Constructing a json hash from a bash associative array

后端 未结 4 732

I would like to convert an associative array in bash to a json hash/dict. I would prefer to use jq to do this as it is already a dependency and I can rely on it to produce w

4条回答
  •  执念已碎
    2020-12-17 00:39

    You can initialize a variable to an empty object {} and add the key/values {($key):$value} for each iteration, re-injecting the result in the same variable :

    #!/bin/bash
    
    declare -A dict=()
    
    dict["foo"]=1
    dict["bar"]=2
    dict["baz"]=3
    
    data='{}'
    
    for i in "${!dict[@]}"
    do
        data=$(jq -n --arg data "$data" \
                     --arg key "$i"     \
                     --arg value "${dict[$i]}" \
                     '$data | fromjson + { ($key) : ($value | tonumber) }')
    done
    
    echo "$data"
    

提交回复
热议问题