Kyon147
Kyon147

Reputation: 798

Velocity loop through JSON

I am using Velocity to try and loop through some JSON data I have in a field in Marketo. I have used the tutorial here to change the JSON into a Velocity Map but have an issue trying to loop through the data which is now a map.

#set( $items = ${abandonedBasket_cList} )

###if( $items.get(7).basketJSON.isEmpty() )
###set( $items.get(7).basketJSON = '[]' )
###end

#foreach ($item in $items)
    #if( $foreach.last )
        #set( $lastitem = $item.basketJSON )
    #end 
#end

#set( $ClientReferrals = '#set( $ClientReferrals = ' + $lastitem + ' ) ' )
#evaluate( $ClientReferrals )


${ClientReferrals[0].itemDesc}       ## outputs "Season Pass Holders"
<br>
${ClientReferrals[1].customerID}     ## outputs "[email protected]"
<br>

I have managed output values from the "map" when using a specific static index like in the example.

The bit I am stuck on is trying to get it to loop through each object using the foreach tool in Velocity as I don't know how to iterate the [index] key as part of the loop.

Update

I have tried to use the code suggested but there is nothing displaying.

#foreach($key in $ClientReferrals.keySet())
   #set($item = $ClientReferrals[$key])
   $item.itemDesc
   ${item.itemDesc}
   $item
   ${item}
#end

If I output what $ClientReferrals looks like this is what I get. Does this look like a Hashmap to you?

[{id=29071940, itemDesc=1.33ct AA Tanzanite 9K Gold Earrings, itemImage=https://cdn.gemporia.com/images/products/300/NJPS19.jpg, itemQuantity=1, itemPrice=£151.00, customerID=1132399, basketURL=https://secure.gemporia.com/basket.aspx, isAuction=false, stock=10, dateAdded=2017-02-15}, {id=29071946, itemDesc=Size J to K AA Tanzanite & White Zircon 9K Gold Ring ATGW 1.08cts, itemImage=https://cdn.gemporia.com/images/products/300/OZVJ80.5.jpg, itemQuantity=1, itemPrice=£89.99, customerID=1132399, basketURL=https://secure.gemporia.com/basket.aspx, isAuction=true, stock=1, dateAdded=2017-02-15}] 

Upvotes: 2

Views: 4623

Answers (1)

Claude Brisson
Claude Brisson

Reputation: 4150

If $ClientReferrals is a map, then you can do:

#foreach($key in $ClientReferrals.keySet())
   #set($item = $ClientReferrals[$key])
   ...
#end

Items won't be sorted by key for an HashMap, they will for a TreeMap.

By the way, to get the last item of an array, you can do:

#set($last_index = $items.size() - 1)
#set($last = $items[$last_index])

Upvotes: 3

Related Questions