0

Its a simple three lines code and i'm unable to understand the error. (I'm trying to create a json file from python and then read and write from it.
Note: hi.json is created everytime i run this code but then the error comes. I have tried both .loads and .load functions.)

Code:

import json
with open("hi.json","a+") as f:
   d=f.read()
   d3=json.loads(d)

Error:

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File"C:\Users\minusv\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s)
File"C:\Users\minusv\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File"C:\Users\minusv\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
minusv
  • 1
  • 1
  • 1
    Take a look at the output of `f.read()`... Then ask yourself (or tell us) why you're opening the file in `a+` mode. – Aran-Fey Oct 01 '17 at 13:20
  • i'm not able to understand. my objective is creating hi.json if not created already. if created then read everything from it first (as i'll be performing some operations based on that) i used f.seek(0) to take account of read function. – minusv Oct 01 '17 at 13:44
  • You can't read an empty file as json. You have to check if the file exists, and if not, use a default value for `d3`. – Aran-Fey Oct 01 '17 at 13:48

0 Answers0