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

使用Power BI/Power Query/M Code将JSON数组按列而非行解析的咨询

完整解决方案M代码

你可以直接替换原有查询的代码,修改文件路径后即可运行:

let
    Source = Json.Document(File.Contents("C:\demo.json")),
    // 定位报告下的行集合
    ReportRows = Source[Reports]{0}[Rows],
    // 提取表头值作为列名
    Header = List.Select(ReportRows, each [RowType] = "Header"){0},
    ColumnNames = List.Transform(Header[Cells], each [Value]),
    // 提取所有Section块的行数据
    Sections = List.Select(ReportRows, each [RowType] = "Section"),
    AllDataRows = List.Combine(List.Transform(Sections, each [Rows])),
    // 转换为表格并展开单元格为列
    RowsToTable = Table.FromList(AllDataRows, Splitter.SplitByNothing(), {"RowInfo"}),
    AddCellValues = Table.AddColumn(RowsToTable, "CellValues", each List.Transform([RowInfo][Cells], each [Value])),
    Result = Table.FromColumns(
        List.Zip(AddCellValues[CellValues]),
        ColumnNames
    ),
    // 可选:补充行类型、所属分类字段,不需要可删除以下两步
    AddRowType = Table.AddColumn(Result, "行类型", each AllDataRows{Table.PositionOf(Result, _)}[RowType]),
    AddSectionTitle = Table.AddColumn(AddRowType, "所属分类", each 
        let
            CurrentRow = AllDataRows{Table.PositionOf(AddRowType, _)},
            MatchSection = List.Select(Sections, (s) => List.Contains(s[Rows], CurrentRow)){0}
        in
            try MatchSection[Title] otherwise "汇总项"
    )
in
    AddSectionTitle

核心处理逻辑说明

  • 不需要一开始就全量转表格做冗余的列删除操作,直接定位JSON的目标层级取Reports下的行集合,拆分出表头和数据两部分处理
  • 处理Header的Cells列表:用List.Transform批量提取每个单元格的Value值,直接作为后续表格的列名,实现列表按列映射
  • 处理Section的Rows.1列表:先过滤出所有Section行,用List.Combine把多个Section下嵌套的行集合合并为一个一维列表,统一处理
  • 每行的Cells列表转多列:用List.Zip把所有行的Cells按位置配对,再通过Table.FromColumns直接生成多列表格,匹配提前提取的表头命名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:06:00