Constructing a json hash from a bash associative array

后端 未结 4 739

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:42

    This has been posted, and credited to nico103 on IRC, which is to say, me.

    The thing that scares me, naturally, is that these associative array keys and values need quoting. Here's a start that requires some additional work to dequote keys and values:

    function assoc2json {
        typeset -n v=$1
        printf '%q\n' "${!v[@]}" "${v[@]}" |
            jq -Rcn '[inputs] |
                    . as $v |
                    (length / 2) as $n |
                    reduce range($n) as $idx ({}; .[$v[$idx]]=$v[$idx+$n])'
    }
    
    
    $ assoc2json a
    {"foo\\ bar":"1","b":"bar\\ baz\\\"\\{\\}\\[\\]","c":"$'a\\nb'","d":"1"}
    $
    

    So now all that's needed is a jq function that removes the quotes, which come in several flavors:

    • if the string starts with a single-quote (ksh) then it ends with a single quote and those need to be removed
    • if the string starts with a dollar sign and a single-quote and ends in a double-quote, then those need to be removed and internal backslash escapes need to be unescaped
    • else leave as-is

    I leave this last iterm as an exercise for the reader.

    I should note that I'm using printf here as the iterator!

提交回复
热议问题