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

Python无法从JSON中提取available字段问题求助

解决JSON中available字段提取后Excel显示为空的问题

问题根源

JSON接口返回的available字段是布尔类型(True/False),直接通过openpyxl写入Excel时,Excel对布尔值的默认显示逻辑可能导致内容异常;同时代码中存在循环变量名重复的潜在风险,易引发逻辑混淆。

解决方案

1. 转换布尔值为可显示格式

将布尔类型的available值转换为字符串或业务友好的文本,确保Excel能正常渲染内容:

# 方案1:转为"True"/"False"字符串
varavailability = "" if idx >= len(variants) else str(variants[idx].get('available', False))

# 方案2:转为业务可读文本(如"In Stock"/"Out of Stock")
varavailability = "" if idx >= len(variants) else "In Stock" if variants[idx].get('available', False) else "Out of Stock"

2. 修复循环变量名冲突

外层循环用product作为变量名,内层循环用idx作为索引变量,避免变量覆盖导致的逻辑混乱:

# 外层循环修改
for product in html['products']:
    title = product.get('title')
    id1 = product.get('id')
    product_type = product.get('product_type')
    images = [img.get('src', '') for img in product.get('images', [])]
    products.append((title, id1, product_type, images))
    variants = [var for var in product.get('variants')]
    # 内层循环改用idx作为索引
    for idx in range(max(len(images), len(variants))):
        imgsrc = "" if idx >= len(images) else images[idx]
        varsku = "" if idx >= len(variants) else variants[idx].get('sku', '')
        varprice = "" if idx >= len(variants) else variants[idx].get('price', '')
        varavailability = "" if idx >= len(variants) else str(variants[idx].get('available', False))
        sheet.append([title, "'" + str(id1), product_type, imgsrc, varsku, varprice, varavailability])

3. 优化Excel保存时机(可选)

将Excel保存操作移到所有产品处理完成后,避免重复写入文件,提升效率:

print("Saving to excel ...")
for product in html['products']:
    # 产品处理逻辑...
    for idx in range(max(len(images), len(variants))):
        # 行写入逻辑...
# 所有产品处理完成后统一保存
f.save(f"result230102.xlsx")

验证方法

在代码中添加打印语句,确认available字段的真实取值:

# 在variants赋值后添加
for var in variants:
    print(f"Variant available status: {var.get('available')}, type: {type(var.get('available'))}")

通过打印结果确认字段存在且为布尔类型,再验证转换后的取值是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:20:49