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?

6
  • 1
    The data you posted works for me on python 2.7. Maybe check the input file? Commented Apr 29, 2019 at 7:31
  • Possible duplicate of Python ValueError: No JSON object could be decoded Commented Apr 29, 2019 at 7:32
  • 1
    What do you mean by "randomly" ? The error does not happen every time ? If so at which frequency ? Commented Apr 29, 2019 at 7: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 atry: ... except ...: ... around the json.load and in the except clause dump the file name (or better path) and file content Commented Apr 29, 2019 at 8: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. Commented Apr 29, 2019 at 8:05

2 Answers 2

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)    
Sign up to request clarification or add additional context in comments.

1 Comment

According with json.load documentation, you should pass an file-like object
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.