tags:

views:

174

answers:

1

I have a CGI query like this: 'a=1&b=2&c=3'.

I want to extract it in an associative array A such as $A[a]=1, $A[b]=2 and $[c]=3.

I found this way, but I would like to find a simpler (shorter) way to this :

QUERY='a=1&b=2&c=3'
typeset -a T
T=( ${(s:&:)QUERY} )
typeset -A A
A=()
for v in $T; do
    A+=( ${(s:=:)v} )
done

(bonus: find a way to handle URL encoded values)

A: 

For those interested, this code parses GET and POST parameters and stores them in the global associative array QUERY_PARAMETERS.

function parse_query_string()
{
    local query="$1"
    local -a pairs
    pairs=( ${(s:&:)query} )
    for v in $pairs; do
        QUERY_PARAMETERS+=( ${(s:=:)v} ) # todo: handle parameters without =
    done
    for name in ${(k)QUERY_PARAMETERS}; do
        local value="$QUERY_PARAMETERS[$name]"
        QUERY_PARAMETERS[$name]="$(url_decode "$value")"
    done
}

function url_decode()
{
    setopt extendedglob
    local d=${1//\%(#b)([0-F][0-F])/\\\x$match[1]}
    d=${d//+/ }
    echo "$d"
}

parse_query_string "$QUERY_STRING"
parse_query_string "$(cat)"
Jazz