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

如何在Azure Logic App中提取字符串内嵌套JSON的错误信息

提问内容

我在使用Azure Logic App时遇到问题,向各位寻求帮助:
失败的HTTP请求返回如下JSON输出:

{
  "error": {
    "code": "",
    "message": "Http request failed with statusCode=BadRequest : {\"error\":{\"code\":\"ValidationFailed\",\"message\":\"Validation of indicator content failed.\",\"target\":\"body\",\"details\":[{\"code\":\"ValidationFailed\",\"message\":\"The value 1 is not a valid domain name.\",\"target\":\"domainName\"}]}}; ",
    "innerError": {
      "date": "2021-11-25T11:12:09",
      "request-id": "",
      "client-request-id": ""
    }
  }
}

我希望提取其中message字段的内容告知用户应用失败原因,但该字段值是字符串,内部嵌套了JSON对象。我需要先处理掉对象前后的冗余字符,再解析JSON来提取内部字段,我想要获取的目标对象结构如下:

{
  "error": {
    "code": "ValidationFailed",
    "message": "Validation of indicator content failed.",
    "target": "body",
    "details": [
      {
        "code": "ValidationFailed",
        "message": "The value 1 is not a valid domain name.",
        "target": "domainName"
      }
    ]
  }
}

我可以在Azure Logic App中使用JavaScript,请问如何实现字段提取?我目前尝试先解析顶层JSON,再解析message字段,但因该字段不是对象类型而失败。我最终希望输出如下格式的提示:

ValidationFailed: Validation of indicator content failed

或更完善的格式:

ValidationFailed: Validation of indicator content failed - The value 1 is not a valid domain name.

我之前仅使用Logic App原生能力未解决问题,Azure支持内联JavaScript执行,所以希望获得JavaScript实现方案。我判断只要在解析JSON前移除"Http request failed with statusCode=BadRequest :"这段前缀和末尾的分号,即可正常解析内部嵌套的JSON对象:

{\"error\":{\"code\":\"ValidationFailed\",\"message\":\"Validation of indicator content failed.\",\"target\":\"body\",\"details\":[{\"code\":\"ValidationFailed\",\"message\":\"The value 1 is not a valid domain name.\",\"target\":\"domainName\"}]}};

我已参考过以下文章但未找到适配方案:

  • Python 2.7 Isolate multiple JSON objects in a string
  • What is the correct JSON content type?

解决方案

你可以直接使用以下内联JavaScript代码实现需求:

// 替换为你Logic App中对应HTTP请求动作的实际名称
const httpActionOutput = workflowContext.actions['HTTP请求'].outputs.body;
const topLevelResult = JSON.parse(httpActionOutput);
const rawErrorMsg = topLevelResult.error.message;

// 裁剪冗余前后缀,正则适配不同状态码的前缀场景
const cleanedJson = rawErrorMsg
  .replace(/^Http request failed with statusCode=\w+ : /, '')
  .replace(/; *$/, '');

const nestedError = JSON.parse(cleanedJson);

// 拼接输出文本,自动适配有无详情的场景
const baseOutput = `${nestedError.error.code}: ${nestedError.error.message}`;
const finalOutput = nestedError.error.details?.length 
  ? `${baseOutput} - ${nestedError.error.details[0].message}`
  : baseOutput;

return finalOutput;

注意事项

  • 代码中HTTP请求要替换为你自己Logic App里发送失败请求的动作名称
  • 前缀匹配用了正则适配不同状态码的场景,不用固定写死BadRequest,兼容性更强
  • 对details字段做了可选链判断,没有详情内容时自动返回基础格式的提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:04