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

Power Automate:扁平化JSON对象,提取动态嵌套数组中所有附件

处理Outlook Graph API嵌套附件的扁平化方案

核心思路

用递归遍历的方式,深度优先搜索所有层级的attachments数组,收集每个附件的完整节点数据,同时按需过滤无关字段。这种方式能适配Graph API返回的动态嵌套结构,比xpath/jsonpath更灵活,能获取完整的附件对象。

代码实现(JavaScript示例)

// 递归收集所有层级的附件,可自定义过滤字段
function flattenAttachments(item, filteredFields = null) {
  let attachments = [];

  // 处理当前item的attachments(如果存在)
  if (item.attachments && Array.isArray(item.attachments)) {
    for (const attachment of item.attachments) {
      // 过滤字段:如果指定了保留字段,就生成新对象;否则保留完整节点
      const processedAttachment = filteredFields 
        ? filteredFields.reduce((acc, key) => {
            if (attachment.hasOwnProperty(key)) acc[key] = attachment[key];
            return acc;
          }, {})
        : {...attachment};

      attachments.push(processedAttachment);

      // 递归处理附件中的嵌套attachments(比如附件是带附件的邮件)
      if (attachment.attachments) {
        attachments = attachments.concat(flattenAttachments(attachment, filteredFields));
      }
    }
  }

  return attachments;
}

// 使用示例:假设response是Graph API返回的邮件对象
const graphApiResponse = { /* 你的API返回数据 */ };
// 1. 获取所有完整附件节点
const allFullAttachments = flattenAttachments(graphApiResponse);
// 2. 只保留需要的字段,比如id、name、contentType、contentBytes
const filteredAttachments = flattenAttachments(graphApiResponse, ['id', 'name', 'contentType', 'contentBytes']);

代码说明

  • 递归遍历每个对象的attachments属性,不管嵌套多少层都能覆盖到;
  • 支持自定义过滤字段:如果不需要完整节点,传入需要保留的字段数组即可生成精简对象;
  • 兼容Graph API中“附件包含嵌套附件”的场景(比如内嵌邮件附件又带自己的附件)。

替代方案(Python示例)

如果用Python处理,逻辑类似:

def flatten_attachments(item, filtered_fields=None):
    attachments = []
    if 'attachments' in item and isinstance(item['attachments'], list):
        for attachment in item['attachments']:
            # 过滤字段
            if filtered_fields:
                processed = {k: attachment[k] for k in filtered_fields if k in attachment}
            else:
                processed = attachment.copy()
            attachments.append(processed)
            # 递归处理嵌套附件
            if 'attachments' in attachment:
                attachments.extend(flatten_attachments(attachment, filtered_fields))
    return attachments

# 使用示例
graph_response = { /* API返回数据 */ }
all_attachments = flatten_attachments(graph_response)
filtered = flatten_attachments(graph_response, ['id', 'name', 'contentType', 'contentBytes'])

为什么xpath/jsonpath不够用?

xpath(或jsonpath)适合提取特定路径的属性,但Graph API的嵌套是动态的,且你需要完整的附件节点而非单个属性。递归遍历能动态处理任意深度的嵌套,同时保留完整的对象结构,更适配你的需求。

内容的提问来源于stack exchange,提问作者Johan Spånberg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:04:47