1

Here's the code I'm using to get the data:

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

And here is the raw data from the file: {"status": true, "angle": -0.0, "speed": 0.0, "time": 1556521858546.0}

However, I randomly get the error: No JSON object could be decoded

Any ideas what could be causing it?

Shane Smiskol
  • 952
  • 1
  • 11
  • 38
  • 1
    The data you posted works for me on python 2.7. Maybe check the input file? – codelessbugging Apr 29 '19 at 07:31
  • Possible duplicate of [Python ValueError: No JSON object could be decoded](https://stackoverflow.com/questions/26808814/python-valueerror-no-json-object-could-be-decoded) – amanb Apr 29 '19 at 07:32
  • 1
    What do you mean by "randomly" ? The error does not happen every time ? If so at which frequency ? – Louis Saglio Apr 29 '19 at 07:40
  • *Randomly* getting errors is weird. A computer is a stupid thing: facing same input it should always give same output. Wild guesses of what could happen: reading a wrong file, reading a file before it has been fully written, errors at write time. To make sure, you should use a`try: ... except ...: ...` around the `json.load` and in the except clause dump the file name (or better path) and file content – Serge Ballesta Apr 29 '19 at 08:00
  • Are you sure if file exists? You can add a `import os; os.path.exists(path)` checking in order to avoid file path issues or whatever. – ssoto Apr 29 '19 at 08:05
  • @LouisSaglio I am writing to this file periodically from another python file, while reading the file from this py file. Is that the cause? Could it be reading at the exact moment it's getting written? If so, how can I ensure that it waits until the file is done being written to from another python file? – Shane Smiskol Apr 30 '19 at 00:59

2 Answers2

1

What about randomly occurrence (Please specify case for this),you can also use these 2 code to read file content.

Code 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)

Code 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)    
0

I was writing to the json file from another Python file periodically at the same time, and using the line f.seek(0) immediately before reading the contents drastically helped reduce the number of errors I received. No idea why, but I seem to be having no issues with parsing the file contents now after that.

Shane Smiskol
  • 952
  • 1
  • 11
  • 38