在Jupyter Notebook中读取文件夹内JSON文件遇ValueError报错求助
问题原因分析
- 路径转义错误:Windows路径中的
\是转义字符,直接写"D:\FastCharge"会让\F被解析为无效转义序列,导致路径无法被正确识别。 - 文件获取逻辑错误:
folder是字符串类型,folder[0]取的是字符串的第一个字符"D",而非文件夹内的第一个JSON文件。pd.read_json尝试解析单个字符,完全不符合JSON格式要求,因此抛出ValueError: Expected object or value。
解决方案
方法1:使用os模块处理文件路径
import os import pandas as pd # 用原始字符串避免转义问题,也可以写成"D:\\FastCharge" folder = r"D:\FastCharge" # 筛选文件夹内所有JSON文件(忽略大小写) json_files = [file for file in os.listdir(folder) if file.lower().endswith(".json")] if json_files: # 拼接第一个JSON文件的完整路径 first_json_path = os.path.join(folder, json_files[0]) # 读取JSON文件 df = pd.read_json(first_json_path) print(df.head()) else: print("目标文件夹中未找到JSON文件")
方法2:使用pathlib(Python 3.4+推荐写法)
from pathlib import Path import pandas as pd # 用原始字符串定义路径 folder = Path(r"D:\FastCharge") # 匹配文件夹内所有JSON文件 json_files = list(folder.glob("*.json")) if json_files: df = pd.read_json(json_files[0]) print(df.head()) else: print("目标文件夹中未找到JSON文件")
额外注意事项
- 如果你的JSON文件是每行一个独立JSON对象的格式,需要添加
lines=True参数:pd.read_json(first_json_path, lines=True) - 若读取仍报错,需检查目标JSON文件本身是否存在语法错误(比如缺少括号、引号不匹配等)。
内容的提问来源于stack exchange,提问作者TH3CODEgUy
相关产品推荐
相关产品推荐

