【发布时间】:2019-05-02 18:19:02
【问题描述】:
大家好,我正在尝试将一堆 json 文件加载到我的程序中,但每当我尝试运行此代码时:
import json
import os
import sys
import requests
path = r'C:\Users\'
json_files = [pos_json for pos_json in os.listdir(path) if pos_json.endswith('.json')]
print(json_files)
JsonDictionary = {}
struct = {}
try:
for x in range(len(json_files)):
Jpath = str(path +'\\'+ json_files[x])
file = open(Jpath)
file_s = file.read()
print("File Read: " + str(file_s))
file_data = json.loads(file_s)
print(Jpath)
JsonDictionary = json.load(Jpath)
except IOError as e:
print (e)
print ('IOError: Unable to open json file. Terminating execution.')
exit(1)
print (JsonDictionary)
这是错误输出:
JSONDecodeError Traceback (most recent call last)
<ipython-input-80-0333b738997d> in <module>
24 # print (sys.exc_info())
25 print("File Read: " + str(file_s))
---> 26 file_data = json.loads(file_s)
27 print(Jpath)
28 JsonDictionary = json.load(Jpath)
~\AppData\Local\conda\conda\envs\tensorkeras2\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder
~\AppData\Local\conda\conda\envs\tensorkeras2\lib\json\decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
~\AppData\Local\conda\conda\envs\tensorkeras2\lib\json\decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我得到的只是 JSONDecodeError: Expecting value: line 1 column 1 (char 0)。 我已经看到针对相同错误代码提出的其他解决方案,但它们似乎都不是解决方案。是代码问题还是输入问题?
【问题讨论】:
-
代码看起来不错,也许你有一个空的
json文件? -
@Cartucho 我已经重新检查了所有文件,但它们似乎都不是空的。我也检查了格式,一切似乎都是 json 有效
-
我认为问题在于
json.load(Jpath),因为Jpath是str,但json.load需要一个类似文件的对象-docs.python.org/2/glossary.html#term-file-like-object。顺便问一下,为什么你同时拥有json.loads(file_s)和json.load(Jpath)? -
@Cartucho 即使我完全删除该行,我也会遇到同样的问题。仍然在另一行, file_data = json.loads(file_s) 行。老实说,我的目标是将所有 json 文件数据加载到字典中,以便之后按类别分析它们。即使我从参数中删除字符串,它也会给我相同的结果
-
我认为你应该写完整的错误输出,这样会更容易帮助你。