我需要打开许多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)
答案 0 :(得分: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)