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

如何实现PAYLOAD与payload1间不同键名的data及metadata字段映射

需求与实现方案

给定的两个JSON结构(Python字典形式)

PAYLOAD = {
    "data": {
        'id': 2,
        'rate_service_id': 4,
        'max_weight': 4.5,
        'max_height': 5,
        'max_length': 6.5,
        'max_depth': 3,
        'fee': 1000

    },
    "metadata": {
        "timestamp": "2022-12-15T06:01:49.645358Z",
        "record-type": "data",
        "operation": "insert",
        "partition-key-type": "primary-key",
        "schema-name": "public",
        "table-name": "rates",
        "transaction-id": 124841932694166
    }
}

payload1 = {
    'data': {'length': None,
             "width": None,
             "height": None,
             "weight": None
             },
    'metadata': {
        "timestamp": None,
        "record-type": None,
        "operation": None,
        "partition-key-type": None,
        "schema-name": "",
        "table-name": "",
        "transaction-id": None
    }
}

注:原payload1中未赋值的字段已补充为None,符合Python语法规范。

映射需求

  • data字段映射规则:
    • PAYLOAD.data.max_length → payload1.data.length
    • PAYLOAD.data.max_depth → payload1.data.width
    • PAYLOAD.data.max_height → payload1.data.height
    • PAYLOAD.data.max_weight → payload1.data.weight
  • metadata字段映射规则:直接将PAYLOAD的metadata字段完整覆盖到payload1的metadata字段

实现代码(Python)

# 定义字段映射关系
data_mapping = {
    'max_length': 'length',
    'max_depth': 'width',
    'max_height': 'height',
    'max_weight': 'weight'
}

# 处理data字段映射
for src_key, dest_key in data_mapping.items():
    if src_key in PAYLOAD['data']:
        payload1['data'][dest_key] = PAYLOAD['data'][src_key]

# 处理metadata字段完整映射
payload1['metadata'] = PAYLOAD['metadata'].copy()

# 输出结果
print("映射后的payload1:")
print(payload1)

执行结果

映射后的payload1数据如下:

{
    'data': {'length': 6.5, 'width': 3, 'height': 5, 'weight': 4.5},
    'metadata': {
        'timestamp': '2022-12-15T06:01:49.645358Z',
        'record-type': 'data',
        'operation': 'insert',
        'partition-key-type': 'primary-key',
        'schema-name': 'public',
        'table-name': 'rates',
        'transaction-id': 124841932694166
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:15:11