Azure APIM中JSON转XML的Liquid for循环失效问题求助
Azure API Management Liquid模板循环读取数组失败问题
我遇到了和Stack Overflow帖子《Azure API Management policy for loop not working on array》描述的类似问题,按帖子里的解决方案实现后,Liquid模板仍无法正确读取数组值,求技术支持。
我的转换策略代码如下:
<json-to-xml apply="always" consider-accept-header="true" parse-date="true" /> <set-body template="liquid"> <soapenv:Envelope > <soapenv:Body> <Create xmlns="http://siebel.com/WebService"> <SharedList> {% for item in body.sharedList.contact %} <contact> {% if item.userId %} <UserId>{{item.userId}}</UserId> {% else %} <UserId>Empty</UserId> {% endif %} </contact> {% endfor %} </SharedList> <AssetNum>{{body.Document.AssetNum}}</AssetNum> </CreateSR_Input> </soapenv:Body> </soapenv:Envelope> </set-body> <!-- Set Content-Type header to XML --> <set-header name="Content-Type" exists-action="override"> <value>application/xml</value> </set-header>
示例负载:
{ "assetNum": "", "sharedList": { "contact": [ { "userId": "spokuri" } ] } }
问题排查与解决方案
json-to-xml转换后的结构适配
使用json-to-xml后,JSON数组会被转换为带专属命名空间的XML结构,数组元素被包裹在<json:Array>下,每个元素是<json:Item>。原模板的路径body.sharedList.contact无法定位到数组元素,需调整循环路径:{% for item in body.sharedList.contact.json:Array.json:Item %}修正字段取值路径
示例负载中字段为assetNum,但模板里写的是body.Document.AssetNum,完全不匹配,应改为{{body.assetNum}}(若转换后XML标签首字母大写,可调整为{{body.AssetNum}},建议先测试查看转换后的XML结构确认)。修复标签闭合错误
模板里<Create>标签对应的闭合是</CreateSR_Input>,标签不匹配,需修正为</Create>。
修正后的完整模板
<json-to-xml apply="always" consider-accept-header="true" parse-date="true" /> <set-body template="liquid"> <soapenv:Envelope > <soapenv:Body> <Create xmlns="http://siebel.com/WebService"> <SharedList> {% for item in body.sharedList.contact.json:Array.json:Item %} <contact> {% if item.userId %} <UserId>{{item.userId}}</UserId> {% else %} <UserId>Empty</UserId> {% endif %} </contact> {% endfor %} </SharedList> <AssetNum>{{body.assetNum}}</AssetNum> </Create> </soapenv:Body> </soapenv:Envelope> </set-body> <!-- Set Content-Type header to XML --> <set-header name="Content-Type" exists-action="override"> <value>application/xml</value> </set-header>
内容的提问来源于stack exchange,提问作者siva
相关产品推荐
相关产品推荐

