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

如何使用JoltTransformJson实现指定JSON转换需求?

JSON数据结构转换实现

问题场景

给定如下原始JSON数据:

{
  "table": "table_name",
  "op_type": "U",
  "before": {
    "AAAA": "1-1111",
    "BBBB": "2022-08-31 03:57:01",
    "CCCC": "2023-08-31 23:59:59"
  },
  "after": {
    "AAAA": "1-1112",
    "BBBB": "2022-08-31 10:10:34"
  }
}

需要将其转换为包含合并后字段及变更列记录的目标结构:

{ 
  "AAAA": "1-1112",
  "BBBB": "2022-08-31 10:10:34",
  "CCCC": "2023-08-31 23:59:59",
  "changed_columns": "AAAA, BBBB"
}

转换规则:

  • 所有字段优先取after中的值,after中不存在的字段则沿用before中的值;
  • 添加changed_columns字段,记录所有值发生变更的列名(即before与after中值不同的列)。

解决方案(Python实现)

以下是简洁的Python代码实现,可直接运行得到目标结果:

import json

# 加载原始数据
raw_data = json.loads('''
{
  "table": "table_name",
  "op_type": "U",
  "before": {
    "AAAA": "1-1111",
    "BBBB": "2022-08-31 03:57:01",
    "CCCC": "2023-08-31 23:59:59"
  },
  "after": {
    "AAAA": "1-1112",
    "BBBB": "2022-08-31 10:10:34"
  }
}
''')

before = raw_data["before"]
after = raw_data["after"]

# 合并字段:after覆盖before同名字段
merged = {**before, **after}

# 筛选变更列
changed_cols = [col for col in after if before.get(col) != after[col]]

# 添加变更列字段
merged["changed_columns"] = ", ".join(changed_cols)

# 输出结果
print(json.dumps(merged, indent=2))

代码说明

  1. 字段合并:通过字典解包{**before, **after}实现after字段对before字段的覆盖,满足"优先取after值"的规则;
  2. 变更列筛选:遍历after中的所有列,对比其在before中的值,筛选出值不同的列;
  3. 结果组装:将合并后的字段与变更列字符串组合,最终输出符合要求的JSON结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:01:37