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

Python读取URL的JSON后弹出userId为5的Post条目并保存到本地的实现方法

代码调整方案

你现有代码的核心问题有3个:

  • 自定义的测试列表mylist和你实际请求拿到的site_info真实数据没有关联,这部分逻辑完全无用可以删除
  • 正向遍历列表时直接删除元素会出现索引错位,导致漏删符合条件的数据
  • 缺少将处理后的结果写入本地JSON文件的逻辑

修正后的完整代码

import json
import urllib.request

url = "https://jsonplaceholder.typicode.com/posts"
# 请求并解析JSON数据
data = urllib.request.urlopen(url).read().decode()
site_info = json.loads(data)

# 过滤掉所有userId为5的内容,这里用列表推导式比pop操作更高效稳定,不会出现索引问题
filtered_posts = [post for post in site_info if post["userId"] != 5]

# 写入本地文件,indent=2用于格式化JSON输出,方便阅读
with open("filtered_posts.json", "w", encoding="utf-8") as f:
    json.dump(filtered_posts, f, ensure_ascii=False, indent=2)

# 可选:打印验证结果
print(f"原数据共{len(site_info)}条,过滤后剩余{len(filtered_posts)}条")

如果你必须要求用pop方法删除元素实现需求,就用反向遍历的方式避免索引错位,替换过滤逻辑即可:

# 反向遍历索引,从最后一个元素往前删,不会影响未遍历的元素索引
for i in range(len(site_info)-1, -1, -1):
    if site_info[i]["userId"] == 5:
        site_info.pop(i)

# 此时直接写处理后的site_info即可
with open("filtered_posts.json", "w", encoding="utf-8") as f:
    json.dump(site_info, f, ensure_ascii=False, indent=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:15:02