【问题标题】:No JSON object could be decoded, however the input is in JSON format无法解码 JSON 对象,但输入为 JSON 格式
【发布时间】:2019-04-29 07:28:48
【问题描述】:

这是我用来获取数据的代码:

def read_phantom():
  try:
    with open(phantom_file, "r") as f:
      return json.load(f)
  except:
    return {"status": False}

这是来自文件的原始数据:{"status": true, "angle": -0.0, "speed": 0.0, "time": 1556521858546.0}

但是,我随机得到错误:No JSON object could be decoded

任何想法可能导致它?

【问题讨论】:

  • 您发布的数据适用于我在 python 2.7 上。也许检查输入文件?
  • “随机”是什么意思?错误不会每次都发生?如果是这样,在哪个频率?
  • 随机出错很奇怪。计算机是一个愚蠢的东西:面对相同的输入,它应该总是给出相同的输出。对可能发生的事情的疯狂猜测:读取错误的文件,在文件完全写入之前读取文件,写入时出错。为确保,您应该在json.load 周围使用try: ... except ...: ...,并在except 子句中转储文件名(或更好的路径)和文件内容
  • 您确定文件是否存在?您可以添加import os; os.path.exists(path) 检查以避免文件路径问题或其他问题。

标签: python json


【解决方案1】:

随机出现怎么办(请注明大小写),您也可以使用这2个代码读取文件内容。

代码 1

    import json
    def read_phantom():
      try:
            with open('file_path/phantom_file') as json_file:  
                data = json.load(json_file)
            return (data)
      except:
        return {"status": False}

    record = read_phantom()
    print (record)

代码 2

    def read_phantom():
      try:
        content = []
        f = open('phantom_file','r')
        for line in f:
            cont = line.rstrip("\n")
            content.append(cont)
        return (content)
      except:
        return {"status": False}    

    record = read_phantom()
    print (record)    

【讨论】:

  • 根据json.load 文档,您应该传递一个类似文件的对象
【解决方案2】:

我同时定期从另一个 Python 文件写入json 文件,并在读取内容之前立即使用f.seek(0) 行大大减少了我收到的错误数量。不知道为什么,但在那之后我似乎对解析文件内容没有任何问题。

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2023-03-12
    • 2014-05-17
    • 2013-01-19
    相关资源
    最近更新 更多