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

如何用Python批量搜索JSON文件,筛选含特定属性值的文件?

问题解决:筛选符合条件的JSON文件

代码中的核心错误

  • 路径匹配错误:glob.glob的路径里多余了$符号,导致无法正确匹配目标文件
  • JSON结构访问错误:attributes是数组而非嵌套字典,不能用json_file["attributes"]["values"]["GrapeCity"]访问,正确获取第一个元素value的方式是json_file["attributes"][0]["value"]
  • 缺少筛选判断逻辑:没有对value是否等于"GrapeCity"做判断,而是直接尝试取值,导致无意义的KeyError捕获
  • 存储内容不符合需求:原代码错误地存储不存在的取值,而非符合条件的文件信息

修正后的代码

import json
import glob

src = "./Assets/json"
data = []

# 修正路径,去掉多余的$符号
files = glob.glob(f'{src}/*', recursive=True)

for single_file in files:
    with open(single_file, 'r') as f:
        try:
            json_file = json.load(f)
            # 先检查attributes数组非空,再判断第一个对象的value是否为"GrapeCity"
            if len(json_file.get("attributes", [])) > 0 and json_file["attributes"][0]["value"] == "GrapeCity":
                # 将符合条件的文件名存入列表,也可根据需求存储完整JSON内容
                data.append(single_file)
        except (KeyError, json.JSONDecodeError) as e:
            print(f'跳过文件 {single_file},错误原因:{str(e)}')

data.sort()
print("符合条件的文件列表:")
print(data)

# 如需导出为CSV,取消下方注释并导入csv模块
# import csv
# from datetime import datetime
# date = datetime.now()
# csv_filename = f'{str(date)}.csv'
# with open(csv_filename, "w", newline="", encoding="utf-8") as f:
#     writer = csv.writer(f)
#     for file_path in data:
#         writer.writerow([file_path])
# print(f"已导出符合条件的文件列表到 {csv_filename}")

代码说明

  1. 修正了glob的路径匹配逻辑,使用变量拼接路径提升可读性
  2. 增加了attributes数组非空判断,避免数组为空时触发索引错误
  3. 明确筛选逻辑:判断第一个属性的value是否等于"GrapeCity",符合条件则将文件名加入结果列表
  4. 扩展异常捕获范围,新增json.JSONDecodeError处理无效JSON文件的情况
  5. 保留CSV导出的可选代码,可根据需求启用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:40:58