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

Python调用API返回指定对象及数据筛选存储方法咨询

问题解决方法

你现有代码的核心问题是误用了json.dumps():该方法是将Python对象序列化为JSON字符串,无法直接做后续的键值访问,你需要将API返回的JSON响应转为Python原生的字典/列表结构,直接用requests自带的.json()方法即可。


1. 实现返回links字段的函数

以下代码和你PowerShell的Get-APIUser功能完全对齐:

import requests

def get_apiuser():
    uri = 'https://api.app.com/v1/users.json'
    headers = {'Api-Key':'Insert Key Here'}

    try:
        response = requests.get(uri, headers=headers)
        # 主动捕获4xx/5xx类的请求错误
        response.raise_for_status()
        # 解析JSON响应后直接返回links字段,对应PowerShell的$Response.links
        return response.json()['links']
    except requests.exceptions.RequestException as error:
        print(f"请求出错:{error}")
        # 出错返回空列表,避免后续处理逻辑报错
        return []

2. 筛选指定用户并存为变量

对应PowerShell的Where-Object筛选逻辑,可以用两种方式实现匹配:

# 调用函数获取links下的所有用户列表
user_list = get_apiuser()

target_email = "Insert User Email Here"
# 方法1:匹配所有符合条件的用户,返回列表
matched_users = [user for user in user_list if user['email'] == target_email]
# 方法2:仅取第一个匹配的用户,找不到则返回None(无匹配时不会报错)
user = next((user for user in user_list if user['email'] == target_email), None)

3. 后续使用用户变量

和PowerShell的$User.accountStatus调用逻辑类似,Python用字典键访问即可:

# 先判断用户存在再做操作,避免空值报错
if user and user['accountStatus'] != 'active':
    try:
        # 你的业务处理逻辑
        pass
    except Exception as e:
        print(f"处理出错:{e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:45:03