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

Python版jsonpath批量解析JSON文件全返回False问题求助

问题解决:批量JSON文件用jsonpath解析返回False

你的问题核心是jsonpath函数的参数使用错误:你直接把文件名传给了jsonpath,但它需要的是已经加载完成的JSON数据对象,而非文件路径或名称。

修正后的代码

import os
import json
from jsonpath import jsonpath  # 确保导入正确的jsonpath库

json_path = "/content/drive/MyDrive/dataset_demo/results"

for file_json in os.listdir(json_path):
    if file_json.endswith('.json'):
        # 拼接完整文件路径,避免目录切换带来的路径问题
        full_path = os.path.join(json_path, file_json)
        # 打开并加载JSON文件内容为Python可识别的数据结构
        with open(full_path, 'r', encoding='utf-8') as f:
            try:
                data = json.load(f)
                # 用加载后的JSON对象执行jsonpath查询
                nums_comment = jsonpath(data, '$.node.edge_media_to_comment[*]')
                nums_likes = jsonpath(data, '$.node.edge_media_preview_like[*]')
                print(nums_comment, nums_likes)
            except json.JSONDecodeError:
                print(f"文件 {file_json} 不是有效的JSON格式,跳过解析")

关键修正说明

  • 新增json.load(f):将文件文本内容解析为Python字典/列表(JSON对应的数据结构),这是jsonpath函数能识别的合法输入类型。
  • 使用os.path.join拼接完整路径:即使切换了工作目录,也能确保文件路径的正确性,让代码更健壮。
  • 增加异常捕获:处理可能存在的JSON格式错误文件,避免程序中途崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:40:24