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

API JSON响应循环提取指定卖家商品数据问题排查

修复后的Python脚本实现

问题核心

原脚本仅检查商品的第一个offer,若不匹配直接跳过整个商品,未遍历所有offer导致无法定位目标卖家(示例BBBBBBBB)的数据。需调整逻辑,遍历每个商品的全部offer,匹配卖家后提取offerCSV和stockCSV的最后有效值。

简化API响应示例

{
  "products": [
    {
      "productId": "PROD001",
      "offers": [
        {
          "sellerId": "AAAAAA",
          "offerCSV": ["10.0", "12.0"],
          "stockCSV": ["50", "45"]
        },
        {
          "sellerId": "BBBBBBBB",
          "offerCSV": ["15.0", "14.5"],
          "stockCSV": ["30", "28"]
        }
      ]
    },
    {
      "productId": "PROD003",
      "offers": [
        {
          "sellerId": "BBBBBBBB",
          "offerCSV": ["8.0", "7.5", "7.0"],
          "stockCSV": ["100", "90", "85"]
        }
      ]
    }
  ]
}

修复后的脚本代码

import json

# 实际场景中替换为API调用逻辑
api_response = '''
{
  "products": [
    {
      "productId": "PROD001",
      "offers": [
        {
          "sellerId": "AAAAAA",
          "offerCSV": ["10.0", "12.0"],
          "stockCSV": ["50", "45"]
        },
        {
          "sellerId": "BBBBBBBB",
          "offerCSV": ["15.0", "14.5"],
          "stockCSV": ["30", "28"]
        }
      ]
    },
    {
      "productId": "PROD002",
      "offers": [
        {
          "sellerId": "CCCCCC",
          "offerCSV": ["20.0"],
          "stockCSV": ["10"]
        }
      ]
    },
    {
      "productId": "PROD003",
      "offers": [
        {
          "sellerId": "BBBBBBBB",
          "offerCSV": ["8.0", "7.5", "7.0"],
          "stockCSV": ["100", "90", "85"]
        }
      ]
    }
  ]
}
'''

target_seller = "BBBBBBBB"
output = []

# 解析响应数据
data = json.loads(api_response)

for product in data["products"]:
    prod_id = product["productId"]
    # 遍历当前商品的所有offer
    for offer in product["offers"]:
        if offer["sellerId"] == target_seller:
            # 取数组最后一个有效值,兼容空数组情况
            last_offer = offer["offerCSV"][-1] if offer["offerCSV"] else None
            last_stock = offer["stockCSV"][-1] if offer["stockCSV"] else None
            output.append({
                "productId": prod_id,
                "lastOfferPrice": last_offer,
                "lastStockQuantity": last_stock
            })
            # 找到目标offer后跳出当前商品的循环,避免重复处理
            break

# 打印结果
for item in output:
    print(item)

期望输出

{'productId': 'PROD001', 'lastOfferPrice': '14.5', 'lastStockQuantity': '28'}
{'productId': 'PROD003', 'lastOfferPrice': '7.0', 'lastStockQuantity': '85'}

关键修改点

  • 将单offer检查改为遍历商品下的所有offer
  • 通过数组索引[-1]直接获取最后一个有效值
  • 匹配到目标卖家后跳出当前商品的offer循环,提升效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:12:11