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

请求协助拆分SQL输出的含姓名类字段的JSON对象

需求描述

我从SQL语句得到如下JSON对象:

{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "first_name":{
      "old":"rak",
      "new":"raki"
   },
   "fam_name":{
      "old":"gow",
      "new":"gowda"
   }
}

除first_name、fam_name外,还可能出现initial、nickname这类姓名相关字段。需要将该JSON拆分为多个独立的JSON对象,每个对象保留idno、user、operation、timestamp公共字段,仅包含一个姓名类字段,拆分示例如下:

拆分后第一个JSON:

{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "first_name":{
      "old":"rak",
      "new":"raki"
   }
}

拆分后第二个JSON:

{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "fam_name":{
      "old":"gow",
      "new":"gowda"
   }
}
实现方案

可以用Python编写脚本完成拆分,步骤如下:

  1. 定义所有可能出现的姓名类字段列表
  2. 提取原始JSON中的公共字段
  3. 遍历姓名类字段,若原始JSON中存在该字段,则将公共字段与该字段组合成新的JSON对象

示例代码:

import json

# 原始JSON数据
original_json = '''
{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "first_name":{
      "old":"rak",
      "new":"raki"
   },
   "fam_name":{
      "old":"gow",
      "new":"gowda"
   }
}
'''

# 解析原始JSON
data = json.loads(original_json)

# 定义所有可能的姓名类字段
name_fields = ["first_name", "fam_name", "initial", "nickname"]

# 提取公共字段
common_fields = {k: v for k, v in data.items() if k not in name_fields}

# 生成拆分后的JSON列表
split_jsons = []
for field in name_fields:
    if field in data:
        split_obj = common_fields.copy()
        split_obj[field] = data[field]
        split_jsons.append(split_obj)

# 输出拆分结果
for idx, obj in enumerate(split_jsons, 1):
    print(f"拆分后的第{idx}个JSON:")
    print(json.dumps(obj, indent=3))

运行代码后,会输出符合需求的拆分结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:25:17