python - json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)object_pairs_hook=object_pairs_hook,**kw)
问题描述
我需要打开许多 json 文件并将它们写入一个 csv 文件我编写了一个用于读取一个文件的代码,但是当我想将所有文件附加在一起时,我收到了回溯。
我的代码是
path_to_json = r'\path'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
json_text_list = []
for index, js in enumerate(json_files):
with open(os.path.join(path_to_json, js), encoding="utf8") as json_file:
json_text_list.append(json.load(json_file))
json_text = json.load(json_file)
错误:
File "C:\Users\and\Desktop\t.py", line 18, in <module>
json_text = json.load(json_file)
File "C:\Users\and\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\and\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\and\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\and\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
您需要做的是以读取模式打开文件,并调用.read()
文件处理程序上的方法以实际获取内容作为可以由 json 解析的字符串。
这就是为什么我们使用json.loads()
这是解决方案 -
import os
import json
path_to_json = r'\path'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
json_text_list = []
for index, js in enumerate(json_files):
with open(os.path.join(path_to_json, js), 'r') as json_file:
json_data = json.loads(json_file.read())
json_text_list.append(json_data)