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

如何编码处理网络请求,仅获取菜谱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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:24:02