python 讀空的json檔案
阿新 • • 發佈:2018-11-24
讀空的json檔案,python2和python3 的錯誤提示是不一樣的
python2:
ValueError: No JSON object could be decoded
python3:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解決:
針對python2
import json data ={"vf":"ff"} ''' #寫入 with open('tmp.json', 'w') as f: json.dump(data, f)''' try: with open('tmp.json', 'r') as f: k=json.load(f) print(k) except ValueError:
print("empty!")
針對python3
import json data ={"vf":"ff"} ''' #寫入 with open('tmp.json', 'w') as f: json.dump(data, f) ''' try: with open('tmp.json', 'r') as f: k=json.load(f) print(k) except json.decoder.JSONDecodeError: print("empty!")