【问题标题】:Velocity loop through JSON通过 JSON 的速度循环
【发布时间】:2017-07-04 12:10:27
【问题描述】:

我正在使用 Velocity 尝试遍历我在 Marketo 的一个字段中的一些 JSON 数据。我使用 the tutorial here 将 JSON 更改为速度图,但在尝试循环遍历现在是地图的数据时遇到问题。

#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 "jill@example2.com"
<br>

当使用示例中的特定静态索引时,我已管理“地图”中的输出值。

我坚持的一点是试图让它使用 Velocity 中的 foreach 工具循环遍历每个对象,因为我不知道如何将 [index] 键作为循环的一部分进行迭代。

更新

我已尝试使用建议的代码,但没有显示任何内容。

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

如果我输出 $ClientReferrals 的样子,这就是我得到的。这在你看来像一个 Hashmap 吗?

[{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}] 

【问题讨论】:

    标签: velocity marketo


    【解决方案1】:

    如果$ClientReferrals 是一张地图,那么你可以这样做:

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

    HashMap 的项目不会按键排序,TreeMap 会按键排序。

    顺便说一句,要获取数组的最后一项,可以这样做:

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

    【讨论】:

    • 更新了我的评论,因为我无法使用建议的代码。任何想法? :)
    • 是的:看起来 $ClientReferrals 不是地图,而是地图数组,而我认为你有一个地图 id->item。地图显示为{...},数组显示为[...]
    • 我真的不明白你为什么不能做#foreach($item in $ClientReferrals)
    • 我不知道为什么它以前不起作用(可能是我的错字)但是你的建议非常有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多