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

Azure APIM策略嵌套响应体丢失逗号问题咨询

Azure APIM:正确嵌套响应体到result字段并保持JSON格式的方法

问题场景

使用C#脚本的set-body策略时,响应JSON格式正常:

<set-body>@{
JObject response = context.Response.Body.As<JObject>(preserveContent: true);
return response.ToString();
}</set-body>

但改用Liquid模板嵌套响应体到result字段时,返回的JSON格式异常,一级字段间丢失逗号:
使用的策略:

<set-body template="liquid">{"result" : { {{body}} }, "targetUrl": "null", "success": "true"}
</set-body>

实际异常输出:

"code": "1234" "manufacturer": "test" "count": 1

预期输出:

"code": "1234", "manufacturer": "test" , "count": 1

最佳实现方案

方案1:使用C#脚本构造响应(推荐,格式最可靠)

直接通过C#脚本构造包含result的新响应体,既可以直接拼接原字符串,也可以解析为JSON对象后重组,彻底避免格式问题:

方式A:直接拼接原响应字符串(适合确认原响应是合法JSON的场景)

<set-body>@{
    // 保留原响应体内容,避免后续策略无法读取
    var originalBody = context.Response.Body.As<string>(preserveContent: true);
    // 构造新的JSON结构
    return $"{{\"result\": {originalBody}, \"targetUrl\": \"null\", \"success\": \"true\"}}";
}</set-body>

方式B:解析为JSON对象重组(更安全,自动处理格式)

<set-body>@{
    JObject originalResponse = context.Response.Body.As<JObject>(preserveContent: true);
    JObject newResponse = new JObject();
    newResponse["result"] = originalResponse;
    newResponse["targetUrl"] = "null";
    newResponse["success"] = "true";
    return newResponse.ToString();
}</set-body>

方案2:正确使用Liquid模板

如果坚持使用Liquid,需要用json过滤器将原响应对象转换为标准JSON字符串,避免直接输出对象的无格式字符串:

<set-body template="liquid">
{
  "result": {{ body | json }},
  "targetUrl": "null",
  "success": "true"
}
</set-body>

原因说明

之前的Liquid模板直接使用{{body}}时,APIM会将原JSON响应解析为Liquid对象,其默认字符串输出是不带逗号分隔的键值对格式,而非标准JSON,因此导致格式异常。使用json过滤器可以强制输出合法的JSON字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:41:00