无法解码任何JSON对象,但是输入是JSON格式的

2024-06-26 03:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

知道是什么引起的吗?你知道吗


Tags: 代码jsonfalsereadreturndefasstatus
2条回答

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

随机发生的情况如何(请为此指定大小写),您也可以使用这两个代码来读取文件内容。你知道吗

代码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)    

相关问题 更多 >