【问题标题】:Error in reading JSON: No JSON object could be decoded读取 JSON 时出错:无法解码任何 JSON 对象
【发布时间】:2018-03-04 05:29:29
【问题描述】:

我正在使用 glob 读取一组 JSON 文件并将它们存储在一个列表中。列表的长度是 1046。当我一个一个读取 JSON 文件并加载它以运行进一步的代码时,它只在 595 个文件上运行并给出以下错误:

Traceback (most recent call last):
File "removeDeleted.py", line 38, in <module>
d = json.load(open(fn))
File "/usr/lib/python2.7/json/__init__.py", line 291, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

我正在加载这样的 json 文件:

json_file_names = sorted(glob.glob("./Intel_Shared_Data/gtFine/train/*/*.json")) 
for fn in json_file_names:
    #print fn
    #temp = temp + 1
    #count = 0
    d = json.load(open(fn))
    objects = d["objects"]
    for j in range(len(objects)):

谁能建议我摆脱这个错误?

【问题讨论】:

  • 您的一个文件包含无效的 JSON,Python 无法解析。看看是哪一个。
  • 更具体地说,您的文件之一是空的。 json.loads('') 会给出同样的错误。

标签: python json glob


【解决方案1】:

正如 Blender 所说,您需要找出哪些文件包含无效的 JSON。为此,您需要在代码中添加一些调试语句:

json_file_names = sorted(glob.glob("./Intel_Shared_Data/gtFine/train/*/*.json")) 
  for fn in json_file_names:
   #print fn
   #temp = temp + 1
   #count = 0
   try:
       d = json.load(open(fn))
       objects = d["objects"]
       for j in range(len(objects)):
   except ValueError as e:
       print "Could not load {}, invalid JSON".format({})

【讨论】:

    【解决方案2】:

    您的一个 json 文本文件是空的。也许首先看看你是否有任何零大小的文件

    find . -size 0
    

    从终端中的 json 文件目录运行。

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2017-02-26
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多