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

Python中如何将嵌套JSON值保存到变量用于API请求

从API GET响应提取JSON值并用于POST请求

问题场景

需要从API GET请求返回的JSON中提取id值,保存为变量后用于后续POST调用,但尝试提取时触发string indices must be integers错误。

当前代码

import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import objectpath

auth = HTTPBasicAuth("Username", "PAssword")
departmentname = "IT" #sys.argv[1]
url = "http://url.com".format( departmentname ) 
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

response = requests.request(
    "GET",
    url,
    headers=headers,
    auth=auth,
)
r = json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))
#print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
response.json()

API响应示例

{
    "departments": [
        {
            "created_at": "2022-06-01T17:15:32Z",
            "custom_fields": {},
            "description": "IT Service Team",
            "domains": [],
            "head_user_id": 12345,
            "id": 67890,
            "name": "IT",
            "prime_user_id": null,
            "updated_at": "2022-06-07T16:35:25Z"
        }
    ]
}

错误触发操作

执行print(response['departments'][0]['id'][0])时,报错:string indices must be integers


问题原因

  1. response是Response对象而非字典:直接对response用字典索引会操作响应头,而非响应体内容;
  2. r是格式化后的JSON字符串:json.dumps()将解析后的JSON转为字符串,字符串只能用整数索引,无法用键名;
  3. 多余的[0]:id是单个数值而非列表,不需要额外索引。

修正方案

将响应体解析为字典并提取目标值,代码调整如下:

import requests
from requests.auth import HTTPBasicAuth

auth = HTTPBasicAuth("Username", "PAssword")
departmentname = "IT" #sys.argv[1]
url = "http://url.com".format( departmentname ) 
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

# 发送GET请求并解析响应为字典
response = requests.get(url, headers=headers, auth=auth)
data = response.json()

# 提取部门ID
department_id = data['departments'][0]['id']
print(f"提取的部门ID: {department_id}")

# 后续POST调用示例
post_url = "http://url.com/post-endpoint"
post_payload = {
    "department_id": department_id,
    # 其他POST参数
}
post_response = requests.post(post_url, json=post_payload, headers=headers, auth=auth)

关键说明

  • 使用response.json()直接将响应体解析为Python字典,无需手动json.loads(response.text);
  • 提取id时,data['departments'][0]定位到第一个部门对象,再通过['id']获取目标值;
  • 保存的department_id可直接传入POST请求的payload中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:17