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

Python读取JSON文件提取customerPrice与totalAvailability值的问题

批量提取JSON嵌套字段值的Python脚本修改方案

问题分析

原脚本运行失败的核心原因是目标字段为嵌套结构:

  • totalAvailability 位于每个条目的 availability 子对象中
  • customerPrice 位于每个条目的 pricing 子对象中
    直接通过 item['totalAvailability'] 或 item['customerPrice'] 取值会触发KeyError,因为这些字段不存在于顶层条目对象中。

修改后的脚本

import json

# 读取JSON文件
with open('C:/asg/ftpfiles/API/test/resultsing.json') as json_file:
    data = json.load(json_file)

# 批量提取嵌套字段
total_availabilities = [item['availability']['totalAvailability'] for item in data]
customer_prices = [item['pricing']['customerPrice'] for item in data]

# 打印结果
print("总库存列表:", total_availabilities)
print("客户价格列表:", customer_prices)

增强版(含异常处理)

如果JSON中存在部分条目缺少availability或pricing字段的情况,可以加入异常处理避免脚本崩溃:

import json

with open('C:/asg/ftpfiles/API/test/resultsing.json') as json_file:
    data = json.load(json_file)

total_availabilities = []
customer_prices = []

for item in data:
    # 处理totalAvailability
    try:
        avail = item['availability']['totalAvailability']
        total_availabilities.append(avail)
    except KeyError:
        total_availabilities.append(None)  # 缺失时用None填充
    
    # 处理customerPrice
    try:
        price = item['pricing']['customerPrice']
        customer_prices.append(price)
    except KeyError:
        customer_prices.append(None)

print("总库存列表:", total_availabilities)
print("客户价格列表:", customer_prices)

运行结果示例

针对提供的JSON示例,修改后的脚本会输出:

总库存列表: [5053, 8900]
客户价格列表: [9.13, 9.13]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:25:18