bashlistshelldictionary

How to iterate over list of dictionaries in bash


I am currently learning shell scripting and need your help!

> array = [{u'name': u'androidTest', u'arn': u'arn:XXX', u'created':
1459270137.749}, {u'name': u'android-provider2016-03-3015:23:30', u'arn':XXXXX', u'created': 1459365812.466}]

I have a list of dictionary and want to extract the arn value from the dictionary. In python it is pretty simple for example:

for project in array:
   print project['arn']

How will I write the equivalent loop in bash? If I try something like this, it is not working:

for i in "$array"
do
  echo $i['arn']
done

The suggested duplicate is for associative arrays, not a list of associative arrays.


Solution

  • Bash can't nest data structures, so the thing that would correspond to the list of dictionaries doesn't exist natively. Using a relatively recent Bash (4.3 or newer), we can achieve something similar with namerefs:

    # Declare two associative arrays
    declare -A arr1=(
        [name]='androidTest'
        [arn]='arn:XXX'
        [created]='1459270137.749'
    )
    
    declare -A arr2=(
        [name]='android-provider2016-03-3015:23:30'
        [arn]='XXXXX'
        [created]='1459365812.466'
    )
    
    # Declare array of names of associative arrays
    names=("${!arr@}")
    
    # Declare loop variable as nameref
    declare -n arr_ref
    
    # Loop over names
    for arr_ref in "${names[@]}"; do
        # Print value of key 'arn'
        printf "%s\n" "${arr_ref[arn]}"
    done
    

    This returns

    arn:XXX
    XXXXX