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

Python读取JSON提取Item ID仅得20条,原文件含1546条求排查

问题排查与解决

1. 代码逻辑错误:append语句位置不对

你当前的代码里,save_data.append(item_id)写在了for循环的外面,这导致循环遍历完所有条目后,只会把最后一个item_id添加到列表里。不过你说得到了20条,可能实际运行的代码里append在循环内,但还有其他问题?先把这个逻辑修正:

正确代码应该把append移到循环内部:

with open('data.json') as access_json:
    data = json.load(access_json)

def get_item_ids():
    all_items = data['items']
    for item_data in all_items:
        item_id = item_data['item_id']
        save_data.append(item_id)  # 把这行放到循环里

save_data = []

get_item_ids()

with open('item_ids_test.json', 'w') as file:
    json.dump(save_data, file)

2. 确认data['items']的实际长度

如果修正后还是只有20条,那说明data['items']本身就只有20个元素,和你以为的1546条不符。这时候先验证实际长度:

with open('data.json') as access_json:
    data = json.load(access_json)
print(len(data['items']))  # 打印items的实际条目数

同时检查JSON文件结构,确认1546个条目是不是都在items这个键下——有没有可能条目嵌套在其他层级,或者属于其他键?

3. 检查JSON文件是否完整加载

如果len(data['items'])确实远小于1546,那可能是JSON文件读取不完整:

  • 检查data.json有没有格式错误,比如缺括号、逗号,导致json.load提前停止解析;
  • 可以读取整个文件内容再解析,验证完整性:
with open('data.json', 'r') as f:
    content = f.read()
    print(f"文件总字符数:{len(content)}")
    data = json.loads(content)
    print(f"items长度:{len(data['items'])}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:07:35