×

Python 实现京东商品详情 API 数据准确性校验(极简可直接用)

知名用户18007905473 知名用户18007905473 发表于2026-04-24 15:18:54 浏览4 评论0

抢沙发发表评论

前言

我给你最简洁、最实用、程序员直接复制运行的版本,专门校验京东 API 返回的商品数据是否准确、合法、可用。

一、校验核心(只做最重要的)

  1. 校验返回结构是否正常

  2. 商品 ID(sku_id)是否有效

  3. 商品标题是否存在

  4. 价格是否合法(>0)

  5. 主图是否有效

  6. 店铺 / 类目是否存在

  7. 数据格式是否正确(数字、字符串)


二、Python 校验代码(直接用)

python
运行
def check_jd_item_accuracy(json_data):
    """
    京东商品详情API数据准确性校验
    返回:(True/False, 信息说明)
    """
    try:
        # 1. 检查顶层结构是否正确
        if "jd_item_get_response" not in json_data:
            return False, "返回格式错误,无 jd_item_get_response"

        res = json_data["jd_item_get_response"]
        item = res.get("item", {})
        if not item:
            return False, "未获取到商品信息"

        # 2. 商品SKU_ID 校验(必须是数字)
        sku_id = item.get("sku_id")
        if not sku_id or not str(sku_id).isdigit():
            return False, f"sku_id 无效:{sku_id}"

        # 3. 标题校验(不能为空)
        title = item.get("title")
        if not title or len(title) < 5:
            return False, "商品标题无效或过短"

        # 4. 价格校验(必须 > 0)
        price = item.get("price", "0")
        try:
            price_val = float(price)
            if price_val <= 0:
                return False, f"价格异常:{price}"
        except:
            return False, f"价格格式错误:{price}"

        # 5. 主图链接校验
        img_url = item.get("img_url")
        if not img_url or "http" not in img_url:
            return False, "商品主图无效"

        # 6. 店铺信息校验
        shop_name = item.get("shop_name")
        if not shop_name:
            return False, "店铺名称不存在"

        # 7. 类目ID校验
        cid = item.get("cid")
        if not cid:
            return False, "商品类目 cid 不存在"

        # 全部校验通过
        return True, "京东商品数据校验通过,准确有效"

    except Exception as e:
        return False, f"校验异常:{str(e)}"

三、使用示例

python
运行
# 假设这是你调用京东API返回的JSONjson_result = requests.get(api_url, params=params).json()# 执行校验ok, msg = check_jd_item_accuracy(json_result)print(ok, msg)

四、京东 API 标准返回 JSON(用于测试)

json
{
  "jd_item_get_response": {
    "item": {
      "sku_id": "100012345678",
      "title": "Apple iPhone 15 黑色 128G",
      "price": "5999.00",
      "img_url": "https://img14.360buyimg.com/xxx.jpg",
      "shop_name": "京东自营",
      "cid": 9987
    }
  }}

五、这个校验能帮你避免哪些问题?

  • 数据为空导致程序崩溃

  • 价格异常、负数、0 元导致业务错误

  • 商品 ID 无效

  • 图片失效导致搬家 / 铺货失败

  • 字段缺失导致数据分析出错

  • API 异常返回不被发现


六、一句话总结

京东 API 商品数据校验 = 结构正确 + 字段非空 + 数值合法
让你的数据分析、商品搬家、ERP、监控系统100% 稳定不出错


群贤毕至

访客