You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure APIM Liquid策略解析JSON请求体问题咨询

Azure APIM Liquid入站策略解析JSON问题解决

问题场景

请求体

{
  "id":"1234",
  "modelA": {
    "ids": [
      12, 
      22, 
      32
    ]
  },
  "modelB": {
    "a":"3",
    "ids": [
      22,
      32,
      42
    ]
  }
}

现有入站策略

<inbound>
    <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
    </set-header>
    <set-body template="liquid">
    {
        "aaaa":"{{ body.aaaa }}",
        {% assign var1 = '' %}
        {% for item in {{ body }} %}
            {% for id in {{ item.ids }} %}
                {% assign var1 = var1 | push: id %}
            {% endfor %}
        {% endfor %}
        "result": [
            {{ var1  | join: "," }}
        ]
    }
    </set-body>
    <base />
</inbound>

期望输出

{ 
  "result": [
    12, 
    22, 
    32,
    42
  ]
}

问题解答

1. 遍历JSON根节点属性的正确方式

Liquid中遍历JSON对象的属性时,不需要用{{ }}包裹变量,直接使用{% for key, value in body %}的键值对遍历语法即可。因为body是JSON对象而非数组,需要先获取每个属性的键和对应值,再判断值是否包含ids数组,避免遍历到id这类无ids的属性。

修正后的遍历逻辑:

{% assign var1 = empty %}
{% for key, item in body %}
    {% if item.ids %}
        {% for id in item.ids %}
            {% assign var1 = var1 | push: id %}
        {% endfor %}
    {% endif %}
{% endfor %}

2. join方法无逗号分隔的原因

你初始化var1为''(空字符串),Liquid的push过滤器会将数组元素直接拼接成字符串,而非维护数组结构。后续调用join时,实际是对字符串操作,自然不会生成逗号分隔的结果。

正确做法是将var1初始化为空数组:

{% assign var1 = empty %}

这样push操作会往数组中添加元素,使用join: ", "就能得到预期的逗号分隔效果。

完整修正后的策略

<inbound>
    <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
    </set-header>
    <set-body template="liquid">
    {
        "result": [
            {% assign var1 = empty %}
            {% for key, item in body %}
                {% if item.ids %}
                    {% for id in item.ids %}
                        {% assign var1 = var1 | push: id %}
                    {% endfor %}
                {% endif %}
            {% endfor %}
            {{ var1 | uniq | join: ", " }}
        ]
    }
    </set-body>
    <base />
</inbound>

注:添加uniq过滤器用于去重,匹配期望输出中移除重复ID的需求。

内容的提问来源于stack exchange,提问作者Leszek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:25:18