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
相关产品推荐
相关产品推荐

