简体   繁体   中英

Can only load json file from python terminal and not from script, neither works with ujson package

I originally only used ujson as follows. This code has been working for sometime and I'm not sure how I broke it.

import ujson as json

with open('performance_data.json', 'r') as f:
    data = json.load(f)

It just today started throwing a ValueError

ValueError: Expected object or value

I tried loading the .json file using python in terminal with ujson and I got the same error. Then I tried loading it using json package instead of ujson, and it worked fine, in python terminal. So I added in a try except to use json instead of ujson so now my code looks like this

import json
import ujson

with open('performance_data.json', 'r' as f:
    try:
        data = ujson.load(f)
    except ValueError:
        data = json.load(f)

However this is still giving me problems.

json Traceback:

  File "live_paper.py", line 141, in main
    data = json.load(f)
  File "/usr/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I would normally assume that this means the file is empty. However I can run the following code from script and see the file content.

with open('performance_data.json', 'r') as f:
    print(f.readline())

I've checked os.getcwd() is correct from script.

So summarizing, json.load(f) works from terminal but not when the script is ran. In terminal I can sift through my data and everything looks as it should.

ujson.load() works neither in terminal or from script and json.load() doesnt work from script.

The problem is there is no valid json in your file for the module to load. You can verify this by trying to print the contents of the file using f.read() inside of your with statement. I know you have said that you tried this but there is a difference between the file not being empty and having valid json. The function being called will fail if there is not a valid json object found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM