如何在swapi.co中筛选展示指定属性(姓名、体重、身高等)
如何在SWAPI查询中只获取指定属性?
嘿,我刚好处理过类似的需求!SWAPI本身并没有提供服务器端筛选字段的功能,所以我们得在拿到完整响应后,自己在客户端提取需要的内容。下面给你详细说说怎么做:
直接在客户端筛选(最常用的方式)
不管你用什么语言,核心思路都是先获取完整的API返回数据,再从中挑出你需要的字段——姓名(name)、体重(对应API里的mass字段)、身高(对应height)、眼睛颜色(eye_color)、肤色(skin_color)和性别(gender)。
给你举几个实际的代码例子:
JavaScript 示例
// 用fetch获取卢克·天行者的数据 fetch('https://swapi.co/api/people/1/') .then(res => res.json()) .then(fullPersonData => { // 提取我们需要的字段 const simplifiedData = { name: fullPersonData.name, weight: fullPersonData.mass, height: fullPersonData.height, eyeColor: fullPersonData.eye_color, skinColor: fullPersonData.skin_color, gender: fullPersonData.gender }; console.log('筛选后的数据:', simplifiedData); });
Python 示例
import requests # 请求人物数据 response = requests.get('https://swapi.co/api/people/1/') full_data = response.json() # 筛选指定字段 filtered_data = { 'name': full_data['name'], 'weight': full_data['mass'], 'height': full_data['height'], 'eye_color': full_data['eye_color'], 'skin_color': full_data['skin_color'], 'gender': full_data['gender'] } print(filtered_data)
封装成工具函数(复用更方便)
如果需要多次做同样的筛选,不如写个通用函数,避免重复写代码:
JavaScript 工具函数
function getSimplifiedPersonData(fullData) { // 映射我们要的别名和API实际字段名 const fieldMapping = { name: 'name', weight: 'mass', height: 'height', eyeColor: 'eye_color', skinColor: 'skin_color', gender: 'gender' }; // 生成筛选后的对象 return Object.fromEntries( Object.entries(fieldMapping).map(([ourKey, apiKey]) => [ourKey, fullData[apiKey]]) ); } // 使用的时候就很简单 fetch('https://swapi.co/api/people/1/') .then(res => res.json()) .then(data => console.log(getSimplifiedPersonData(data)));
小提醒
一定要注意SWAPI的字段命名哦!比如你说的"体重"在API里叫mass,"身高"是height,别写错了导致拿不到数据~ 如果是查询人物列表的话,只需要遍历每个人物对象,调用上面的筛选逻辑就行啦。
内容的提问来源于stack exchange,提问作者Igor Shvets
相关产品推荐
相关产品推荐

