如何用Python重构API请求日志中的请求体以重发调试请求?
通用重构分散API请求体日志为嵌套JSON结构
手动实现方案
如果不想引入额外依赖,可以自己写一个简单的函数,遍历所有以request_body.开头的键,拆分路径后逐层构建嵌套字典:
def reconstruct_request_body(payload): request_body = {} prefix = "request_body." for key, value in payload.items(): if not key.startswith(prefix): continue # 移除前缀并拆分路径层级 path_segments = key[len(prefix):].split('.') current_level = request_body # 逐层创建嵌套结构 for segment in path_segments[:-1]: if segment not in current_level: current_level[segment] = {} current_level = current_level[segment] # 为最后一层键赋值 current_level[path_segments[-1]] = value return request_body
使用示例:
假设你的日志payload是:
payload = { "request_body.additional_information.sales_channel": "my sales channel", "request_body.additional_information.platform": "my_sales_platform", "request_body.additional_information.lead_time_business_days": 1, "request_body.additional_information.rule_tags": ["my_first_tag", "my_second_tag"], "request_body.destination_zip_code": 22222222, "request_body.origin_zip_code": 11111111, "request_body.products": None, "request_body.shipment_sub_type": None }
调用函数后得到的结果就是你需要的嵌套结构:
reconstructed = reconstruct_request_body(payload) print(reconstructed) # 输出: # { # "origin_zip_code": 11111111, # "destination_zip_code": 22222222, # "additional_information": { # "lead_time_business_days": 1, # "platform": "my_sales_platform", # "sales_channel": "my sales channel", # "rule_tags": ["my_first_tag", "my_second_tag"] # }, # "products": None, # "shipment_sub_type": None # }
如果需要把部分字段(比如邮编)转成字符串,只需在赋值时添加类型转换逻辑:
# 在赋值前判断字段名 if path_segments[-1] in ["origin_zip_code", "destination_zip_code"]: current_level[path_segments[-1]] = str(value) else: current_level[path_segments[-1]] = value
第三方库方案
如果想更简洁地处理这类点分隔键的嵌套转换,可以使用dotty_dict库,它专门用于处理这种"点路径"式的字典操作:
- 先安装库:
pip install dotty_dict
- 实现代码:
from dotty_dict import dotty def reconstruct_request_body(payload): dotty_payload = dotty(payload) request_body = dotty({}) prefix = "request_body." # 遍历所有request_body开头的键,复制到新的dotty对象中 for key in dotty_payload: if key.startswith(prefix): new_key = key[len(prefix):] request_body[new_key] = dotty_payload[key] # 转换为普通字典返回 return dict(request_body)
这个库会自动处理嵌套路径的创建,无需手动写层级遍历逻辑,代码更简洁易读。
为什么硬编码方案不通用
你之前的硬编码方式只能处理固定的几个字段,一旦API端点的请求体结构变化(比如新增字段、嵌套层级改变),就需要修改代码。而上面的通用方案会自动识别所有request_body.前缀的键,不管结构多复杂,都能正确还原成嵌套的请求体对象,完美适配不同端点的日志。
内容的提问来源于stack exchange,提问作者A. Curvina
相关产品推荐
相关产品推荐

