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

如何在Python中从API JSON响应提取特定数据并转为JSON格式用于API POST推送

解决JSON解析与POST格式转换问题

嘿,很高兴看到你在探索Python网络自动化!针对你的问题,我来一步步帮你搞定——从更优雅地提取目标字段,到把结果转成符合POST要求的JSON格式。

首先,优化字段提取逻辑

你之前用pop删除不需要的字段的思路没问题,但其实更安全直观的方式是只保留你需要的字段,这样即使原API返回的结构有变化,也不会因为找不到要删除的键而出错。

然后,转换为POST可用的JSON格式

Python的json模块里的dumps()方法就能轻松把Python字典/列表转成标准JSON字符串,直接用于POST请求的请求体。

改进后的完整代码示例

import json

# 原API响应数据
data_txt = '''{"links": {"self": "https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networks?offset=0&limit=25&expanded=true"}, "items": [{"links": {"self": "https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networks/005056BB-0B24-0ed3-0000-893353264061", "parent": "https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networkaddresses"}, "type": "Network", "value": "10.0.0.0/8", "overridable": "True", "description": "test api put wih postman ", "id": "005056BB-0B24-0ed3-0000-893353264061", "name": "10.0.0.0_8", "metadata": {"timestamp": 1602974037876, "lastUser": {"name": "akankshu_a"}, "domain": {"name": "Global", "id": "e276abec-e0f2-11e3-8169-6d9ed49b625f"}, "ipType": "V_4", "parentType": "NetworkAddress"}}, {"links": {"self": "https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networks/005056BB-0B24-0ed3-0000-893353272647", "parent": "https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networkaddresses"}, "type": "Network", "value": "10.10.210.0/24", "overridable": "False", "description": " ", "id": "005056BB-0B24-0ed3-0000-893353272647", "name": "10.10.210.0_24", "metadata": {"timestamp": 1598427295586, "lastUser": {"name": "akankshu_a"}, "domain": {"name": "Global", "id": "e276abec-e0f2-11e3-8169-6d9ed49b625f"}, "ipType": "V_4", "parentType": "NetworkAddress"}}]}'''

# 解析JSON字符串为Python字典
json_obj = json.loads(data_txt)

# 定义你需要保留的字段列表
required_fields = ['type', 'value', 'overridable', 'description', 'name']

# 提取目标数据:遍历每个item,只保留需要的字段
extracted_data = []
for item in json_obj['items']:
    filtered_item = {}
    for field in required_fields:
        # 注意:原API返回的overridable是字符串类型,很多POST接口要求布尔值,这里做个转换
        if field == 'overridable':
            filtered_item[field] = item[field] == 'True'
        else:
            filtered_item[field] = item[field]
    extracted_data.append(filtered_item)

# 将提取后的Python列表转为JSON字符串(用于POST请求)
json_for_post = json.dumps(extracted_data, indent=4)

# 打印结果验证
print("提取后的JSON格式数据:")
print(json_for_post)

关键细节说明

  1. 安全提取字段:通过required_fields明确指定要保留的字段,避免了pop操作可能出现的KeyError(如果原数据里某个字段缺失的话)。
  2. 类型转换优化:原数据中overridable是字符串"True"/"False",而大多数API的POST请求要求布尔类型(True/False),所以这里加了类型转换,确保数据格式符合目标接口要求。
  3. JSON转换:json.dumps()会把Python的列表/字典结构转成标准JSON字符串,indent=4是为了格式化输出方便查看,实际POST时可以去掉(不影响接口识别)。

结合requests发送POST请求的示例

如果要用requests库推送数据到目标设备,代码大概是这样的:

import requests

# 目标设备的API端点
post_url = "https://your-target-device/api/endpoint"
# 请求头:通常需要指定Content-Type为application/json
headers = {"Content-Type": "application/json"}

# 发送POST请求
response = requests.post(post_url, headers=headers, data=json_for_post)

# 检查请求结果
if response.status_code in [200, 201]:
    print("数据推送成功!")
else:
    print(f"推送失败,状态码:{response.status_code},响应内容:{response.text}")

这样你就能完成从API获取数据、提取目标字段、转换为POST格式的全流程啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:52:41