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

在Power BI的PowerQuery/M中拆分同时含分支与叶子节点的记录

Power Query/M 修复树形JSON违规记录的方案

针对你遇到的树形JSON中同一记录同时包含非空categories(分支)和products(叶子)的违规情况,以下是直接可用的Power Query/M解决方案,实现违规行拆分、合规行保留的需求:

核心思路

  1. 识别每行是否同时存在非空的categories和products列表
  2. 对违规行生成两条记录:一条保留products并将categories设为null;另一条保留categories并将products设为null
  3. 合规行直接保留原记录
  4. 展开生成的记录列表,得到最终可用于后续处理的表

完整M代码

假设你的数据源已经加载为表(比如通过Json.Document解析后转换的表),替换Source为你的实际数据源即可:

let
    Source = 你的JSON数据源(例:Json.Document(File.Contents("你的文件路径.json"))),
    // 添加自定义列,生成拆分后的记录列表
    GenerateSplitRecords = Table.AddColumn(Source, "SplitRecords", each 
        let
            // 判断categories和products是否为非空列表
            hasValidCategories = [categories] <> null and List.IsEmpty([categories]) = false,
            hasValidProducts = [products] <> null and List.IsEmpty([products]) = false
        in
            if hasValidCategories and hasValidProducts then
                // 生成两条拆分记录,不修改其他业务字段
                {
                    Record.TransformFields(_, {{"categories", (x) => null}}),
                    Record.TransformFields(_, {{"products", (x) => null}})
                }
            else
                // 合规记录直接保留原记录的单元素列表
                {_}
    ),
    // 展开记录列表为多行
    ExpandSplitRows = Table.ExpandListColumn(GenerateSplitRecords, "SplitRecords"),
    // 从拆分后的记录重新生成表,保留所有原字段
    FinalTable = Table.FromRecords(ExpandSplitRows[SplitRecords])
in
    FinalTable

关键细节说明

  • 字段判断逻辑:代码中同时判断了字段不为null且不是空列表,适配JSON中可能出现的两种空值情况;如果你的数据中空值仅为空列表或仅为null,可简化判断条件。
  • 保留业务字段:使用Record.TransformFields仅修改categories和products列,原表中的其他字段(如分类ID、名称等)会完整保留。
  • 空值设置:代码中将不需要的列设为null,如果需要设为空列表,只需把null替换为{}即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:52:46