使用Liquid循环遍历API数据匹配位置并提取奖金额问题排查
问题排查:Braze中Liquid循环查找嵌套API数据失败
我正在使用Braze及Liquid逻辑,尝试通过for循环从关联API的嵌套数据中查找指定地区(如US-NJ)的对象,并将对应currentPotAmount保存到本地变量。此前在其他API场景下实现过该功能,但当前代码始终返回未找到(False),现有代码及API返回数据示例如下,请求排查错误:
API返回数据示例
{ "data": { "jackpotGames": [ { "jackpotDetails": { "jackpotId": "01234", "operatorId": "56789", "locations": [ "US-NJ" ], "supportedCurrencies": [ "USD", "CAD" ], "isAutoOptIn": false, "termsAndConditions": "terms would go here", "title": null, "details": null }, "potDetails": [ { "currentPotAmount": 221005.4, "isProgressiveJackpot": true, "level": 1, "potName": "pot1" } ] } ] } }
当前使用的Liquid代码
{% connected_content 'API URL HERE' :save connectedjackpot :retry %} {% assign jurisdiction = "US-NJ" %} {% assign jurisdictionFound = false %} {% for jackpot in connectedjackpot.data %} {% for game in jackpot.jackpotGames %} {% for details in game.jackpotDetails %} {% for location in details.locations %} {% if location.locations contains {{jurisdiction}} %} {% assign jurisdictionFound = true %} {% assign jackpotId = details.jackpotId %} {% assign state = location.locations %} {% break %} {% endif %} {% endfor %} {% endfor %} {% endfor %} {% endfor %}
验证代码
{% if jackpotFound == false %} False {% else %} True {% endif %}
执行后始终返回False,请问问题出在哪里?
错误分析与修正
1. 第一层循环遍历对象而非数组
connectedjackpot.data是对象(包含jackpotGames属性),不是数组,用for jackpot in connectedjackpot.data会遍历对象的键名(比如jackpotGames),导致后续循环完全偏离预期逻辑。
正确做法:直接访问connectedjackpot.data.jackpotGames数组进行遍历。
2. 遍历jackpotDetails的错误
game.jackpotDetails是单个对象,不是数组,用for details in game.jackpotDetails会遍历该对象的所有键(如jackpotId、locations等),而非拿到完整的详情对象。
正确做法:直接将game.jackpotDetails赋值给变量,无需循环。
3. 条件判断的语法和逻辑错误
- Liquid中判断变量不需要用
{{ }}包裹,{{jurisdiction}}写法错误,直接写jurisdiction即可。 location是details.locations数组中的单个字符串(如"US-NJ"),不存在location.locations属性,应该直接判断location == jurisdiction或者details.locations contains jurisdiction。
4. 变量名不一致
验证代码中使用的是jackpotFound,但逻辑代码中定义的是jurisdictionFound,变量名不匹配导致验证逻辑失效。
修正后的完整代码
{% connected_content 'API URL HERE' :save connectedjackpot :retry %} {% assign jurisdiction = "US-NJ" %} {% assign jurisdictionFound = false %} {% assign targetPotAmount = 0 %} {% for game in connectedjackpot.data.jackpotGames %} {% assign details = game.jackpotDetails %} {% if details.locations contains jurisdiction %} {% assign jurisdictionFound = true %} {% assign jackpotId = details.jackpotId %} {% assign state = jurisdiction %} <!-- 获取对应的currentPotAmount --> {% for pot in game.potDetails %} {% assign targetPotAmount = pot.currentPotAmount %} {% break %} {% endfor %} {% break %} {% endif %} {% endfor %}
修正后的验证代码
{% if jurisdictionFound == false %} False {% else %} True {% endif %}
内容的提问来源于stack exchange,提问作者Kylie Nonemaker
相关产品推荐
相关产品推荐

