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

Python如何从ROR API返回数组中按chosen=True条件提取指定字段

解决代码

import requests

parameters = {
    "affiliation": "cambridge university"
}
response = requests.get("https://api.ror.org/organizations", params=parameters)
result = response.json()

# 筛选标记为chosen:true的条目
chosen_item = None
for item in result.get("items", []):
    if item.get("chosen") is True:
        chosen_item = item
        break

if chosen_item:
    org_info = chosen_item.get("organization", {})
    # 提取基础字段
    print(f'"name":"{org_info.get("name", "")}"')
    print(f'"aliases":{org_info.get("aliases", [])}')
    # 筛选type为Child的关联条目
    for rel in org_info.get("relationships", []):
        if rel.get("type") == "Child":
            print(f'"label":"{rel.get("label", "")}","type":"{rel.get("type", "")}"')
else:
    print("未找到符合chosen: true条件的条目")

关键说明

你之前获取到None的核心原因是接口返回结构嵌套:chosen标记在items数组子元素的顶层,而name、aliases、relationships这些字段都存储在子元素下的organization属性内,跳过这一层直接取字段就会返回空值。
代码中全部使用get方法取值,可避免字段缺失时触发报错,不存在的字段会默认返回空字符串或空数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:54:02