如何编码处理网络请求,仅获取菜谱API返回中非null非空的食材字段
菜谱API有效食材提取方案
核心逻辑很简单,利用API固定返回strIngredient1到strIngredient20、strMeasure1到strMeasure20的字段命名规则,遍历序号筛选非空值即可,具体实现参考下方代码:
JavaScript实现
// meal为接口返回的单条菜谱对象 function getValidIngredients(meal) { const validList = [] for (let i = 1; i <= 20; i++) { const ingredient = meal[`strIngredient${i}`]?.trim() const measure = meal[`strMeasure${i}`]?.trim() // 仅保留食材和用量均为有效值的条目 if (ingredient && measure) { validList.push({ 食材: ingredient, 用量: measure }) } } return validList } // 调用示例 const mealData = apiResponse.meals[0] const finalIngredients = getValidIngredients(mealData)
Python实现
def get_valid_ingredients(meal): valid_list = [] for i in range(1, 21): ingredient = meal.get(f'strIngredient{i}', '').strip() measure = meal.get(f'strMeasure{i}', '').strip() if ingredient and measure: valid_list.append({ '食材': ingredient, '用量': measure }) return valid_list # 调用示例 import requests import json resp = requests.get("你的API请求地址") api_data = json.loads(resp.text) meal_data = api_data['meals'][0] final_ingredients = get_valid_ingredients(meal_data)
如果你的需求允许食材存在、用量为空的场景,只需要调整判断条件,把用量为空的情况替换成「适量」之类的默认值即可,逻辑可以灵活调整。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

