gpt4 book ai didi

azure - 需要使用 Azure APIM set-body 策略修改响应

转载 作者:行者123 更新时间:2023-12-02 08:25:42 25 4
gpt4 key购买 nike

我对 Azure APIM 比较陌生,我有一个可以调用的后端,它以格式返回响应

{
"data": {
"attributes": {
"municipalities": []
}
}
}

我想修改响应,以便数据以格式返回

{
"data": {
"municipalities": []
}
}

我尝试过使用设定的体液模板

<outbound>
<set-body template="liquid">
{
"data": {
"municipalities": {{body.data.attributes.municipalities}}
}
}</set-body>
</outbound>

但我得到的回应只是

{
"data": {
"municipalities":
}
}

如果有人可以向我指出我做错了什么,或者是否有更好的方法来做到这一点?

我还尝试使用以下代码来检查是否能够检索“数据”属性,但在 Azure APIM 测试的跟踪部分中出现以下错误

<outbound>
<set-body>
@{
JObject inBody = context.Request.Body.As<JObject>();
return inBody["data"].ToString();
}
</set-body>
</outbound>

错误:

{
"messages": [
{
"message": "Expression evaluation failed.",
"expression": " \n JObject inBody = context.Request.Body.As<JObject>();\n return inBody[\"data\"].ToString(); \n",
"details": "Object reference not set to an instance of an object."
},
"Expression evaluation failed. Object reference not set to an instance of an object.",
"Object reference not set to an instance of an object."
]
}

最佳答案

body.data.attributes.municipalities是一个数组,我们不能把它 "municipalities":直接地。为了满足您修改json数据格式的要求,我们需要编写每个数组项的每个属性。以下是我的步骤供您引用。

我的 json 是:

{
"data": {
"attributes": {
"municipalities": [
{
"name": "hury",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="355d40474c7558545c591b565a58" rel="noreferrer noopener nofollow">[email protected]</a>"
},
{
"name": "mike",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="482521232d082d25292124662b2725" rel="noreferrer noopener nofollow">[email protected]</a>"
}
]
}
}
}

我的液体模板显示为: enter image description here

================================更新========= ===================

首先是代码JObject inBody = context.Request.Body.As<JObject>();您共享的无法获取响应数据。您应该使用JObject inBody = context.Response.Body.As<JObject>(); .

那么对于您提出的“有没有更简单的方法来删除 .attributes 部分”的问题,我提供以下解决方案供您引用。

不要使用液体模板,使用Replace替换"attributes": {与空并使用 Substring删除最后一个 } .

<set-body>@{ 
JObject inBody = context.Response.Body.As<JObject>();
string str = inBody.ToString();
string str1 = str.Replace("\"attributes\": {", "");
string result = str1.Substring(0, str1.Length-1);
return result;
}</set-body>

注意:此方法需要对响应数据格式进行高度规范。

关于azure - 需要使用 Azure APIM set-body 策略修改响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64856029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com