3

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
python
  • 4,403
  • 13
  • 56
  • 103
  • Possible duplicate of [How to iterate over associative array in bash](http://stackoverflow.com/questions/3112687/how-to-iterate-over-associative-array-in-bash) – Benjamin W. Mar 30 '16 at 23:25
  • I tired this answer before but it is not working. – python Mar 30 '16 at 23:30
  • Did you try the right thing? The "like this" in your question is not how the linked answer does it. – Benjamin W. Mar 30 '16 at 23:31
  • Ignore the `like this`, I tried the link you posted but it is not working. I have list of dictionary not an `associate array`. I am trying again and will post the error – python Mar 30 '16 at 23:34
  • 2
    In Bash, a dictionary is called "associative array", and you can't have arrays of them, so the equivalent Bash data structure doesn't exist, in my opinion. – Benjamin W. Mar 30 '16 at 23:35
  • Could you tell me how can I just print out the `associate-array` inside list? Rest I can do from the link – python Mar 30 '16 at 23:38

2 Answers2

10

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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
-5
for project in $array 
do
  echo $project{'arn'}
done

Or in one line:

for project in $array; do echo $project{'arn'}; done
Arif Burhan
  • 507
  • 4
  • 12
  • Did you test this? There's a lot wrong with this answer: access to an element is not `$arrayname{'key'}`, `$array` expands to just the first element... – Benjamin W. Mar 30 '16 at 23:28