Google App Script扁平化处理Facebook Ad API嵌套JSON方案
Facebook广告API嵌套数据扁平化方案(适配Google Data Studio连接器)
适用于Google App Script环境下,处理Facebook Ad API返回的多层嵌套JSON,输出GDS可识别的单层结构化数据,保留分页信息。
核心处理规则
- 顶层
paging字段完整保留,不做任何结构修改,直接透传给连接器做翻页逻辑 - 遍历顶层
data数组中的每个广告实体,按三类拆分提取嵌套内容:- 提取
adcreatives下的素材属性,统一加creative_前缀后平铺到广告行根层级,避免字段重名 - 提取
insights数组(单条广告通常仅返回1条insights记录,取数组首项即可)下的核心指标,包括ad_id、impressions、clicks、spend、统计起止日期date_start/date_stop、触达reach等,直接平铺到根层级 - 遍历
insights内嵌的actions数组,将每个action_type替换.为_后加action_前缀作为键名,对应统计值value作为键值平铺,消除嵌套数组结构
- 提取
- 所有字段合并完成后为纯单层键值对,无残留嵌套对象/数组,符合GDS数据读取要求
可直接运行的App Script代码
function flattenFbAdData(fbApiResponse) { const processed = { rows: [], paging: fbApiResponse.paging || {} }; if (!Array.isArray(fbApiResponse.data)) return processed; fbApiResponse.data.forEach(ad => { const flatRow = {}; // 提取广告实体本身的顶层非嵌套字段 Object.keys(ad).forEach(topKey => { if (!['adcreatives', 'insights'].includes(topKey)) { flatRow[topKey] = ad[topKey]; } }); // 提取adcreatives素材字段 if (ad.adcreatives && ad.adcreatives.data && ad.adcreatives.data.length) { const creative = ad.adcreatives.data[0]; Object.keys(creative).forEach(cKey => { flatRow[`creative_${cKey}`] = creative[cKey]; }); } // 提取insights成效字段 if (ad.insights && ad.insights.data && ad.insights.data.length) { const insight = ad.insights.data[0]; // 配置需要提取的基础指标字段,可根据实际需求增减 const baseMetrics = ['ad_id', 'impressions', 'clicks', 'spend', 'cpc', 'cpm', 'ctr', 'reach', 'date_start', 'date_stop']; baseMetrics.forEach(metric => { if (insight[metric] !== undefined) flatRow[metric] = insight[metric]; }); // 展开actions行为统计数组 if (Array.isArray(insight.actions)) { insight.actions.forEach(action => { const actionKey = `action_${action.action_type.replace(/\./g, '_')}`; flatRow[actionKey] = action.value; }); } } processed.rows.push(flatRow); }); return processed; }
处理后输出格式示例
{ "rows": [ { "id": "23897429834", "name": "618大促引流广告", "status": "ACTIVE", "creative_title": "618全场5折起", "creative_body": "限时3天 点击直达活动页", "ad_id": "23897429834", "impressions": "18723", "clicks": "562", "spend": "168.32", "ctr": "3.00", "reach": "12456", "date_start": "2024-06-15", "date_stop": "2024-06-18", "action_link_click": "498", "action_page_view": "402", "action_add_to_cart": "112", "action_purchase": "37" } ], "paging": { "cursors": { "before": "QVFIUkxr", "after": "QVFIUmx1" }, "next": "下一页接口请求地址" } }
兼容说明
- 代码没有使用高版本语法,兼容所有Google App Script运行时版本,不需要额外开启V8以上特性开关
- 字段前缀规则可根据实际业务需求调整,只要保证同一条记录下没有重名字段即可
- 如果需要提取
cost_per_action_type、conversions等其他insights下的嵌套数组,参照actions的展开逻辑添加对应处理代码即可 - action_type里的
.必须替换为下划线,否则Google Data Studio会识别字段失败,无法正常拉数
内容的提问来源于stack exchange,提问作者Md Shamsuzzaman
相关产品推荐
相关产品推荐

