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

如何在BigQuery中解析含动态键的JSON数据?

解决方案

这里提供一个纯JS的实现方案,核心是通过遍历对象键值对来展开动态JSON结构:

示例输入数据

先模拟符合你描述的输入表数据:

const inputTable = [
  {
    id: 1,
    otherField: "测试数据1",
    jsonColumn: {
      key_1: { value_1: "a", value_2: "b" },
      key_2: { value_1: "c", value_2: "d" }
    }
  },
  {
    id: 2,
    otherField: "测试数据2",
    jsonColumn: {
      key_3: { value_1: "e", value_2: "f" }
    }
  }
];

转换函数实现

function parseTable(input) {
  const result = [];
  input.forEach(row => {
    // 遍历JSON列的所有动态键值对
    const jsonEntries = Object.entries(row.jsonColumn);
    jsonEntries.forEach(([key, values]) => {
      // 生成新行:保留原行非JSON字段,添加展开的key和对应值
      const { jsonColumn, ...restRow } = row;
      result.push({
        ...restRow,
        key: key,
        value_1: values.value_1,
        value_2: values.value_2
      });
    });
  });
  return result;
}

使用示例与输出结果

调用函数并打印结果:

const outputTable = parseTable(inputTable);
console.log(outputTable);

输出结果将完全匹配你需要的结构:

[
  { id: 1, otherField: "测试数据1", key: "key_1", value_1: "a", value_2: "b" },
  { id: 1, otherField: "测试数据1", key: "key_2", value_1: "c", value_2: "d" },
  { id: 2, otherField: "测试数据2", key: "key_3", value_1: "e", value_2: "f" }
]

关键说明

  • 用Object.entries()遍历JSON对象的动态键,完全适配任意数量的动态键名
  • 通过解构排除原JSON列,避免输出冗余数据
  • 扩展运算符...restRow完整保留原表的所有非JSON字段,保证输出表与原表的业务字段一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:24:23