-4

This is my JSON file:

{
 "pass": "test", 
 "users": "joel"
}

And this is my Python code:

with open("auth.json", "r") as f:
    data = json.load(f)

This is error I am getting:

Traceback (most recent call last): File "W:/ComputerScienceDiceGame/dice.py", line 21, in data = json.load(f.read()) File "C:\Python33\lib\json__init__.py", line 268, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read'

I know this is probably easy but I can't find the root cause of the issue.

Joel Teer
  • 1
  • 4

1 Answers1

0

Pick one:

data = json.load(f)
data = json.loads(f.read())

The point here is, .load loads JSON from a reader (file descriptor), while .loads loads JSON from a string that's already read into memory/buffer.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • data = json.loads(f.read()) File "C:\Python33\lib\json\__init__.py", line 316, in loads return _default_decoder.decode(s) File "C:\Python33\lib\json\decoder.py", line 354, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 1 column 34 - line 1 column 67 (char 33 - 66) – Joel Teer Oct 01 '18 at 09:37
  • @JoelTeer Then your file may be corrupt or contains invalid JSON. – iBug Oct 01 '18 at 09:38
  • My json should be fine because the program enters it itself – Joel Teer Oct 01 '18 at 09:39
  • @JoelTeer The error message says there are "extra data", maybe check again? – iBug Oct 01 '18 at 09:43
  • `auth = { "users": usernamelow, "pass": password } #Converting the variables/inputs to JSON dump = json.dumps(auth) #Gathers data print (dump) #Debug print with open('auth.json', 'a') as outfile: #Opens the file and adds data to it json.dump(auth, outfile)` – Joel Teer Oct 01 '18 at 09:50
  • I just commented out the bit that writes the json to the file and had no problems. I'm rather confused – Joel Teer Oct 01 '18 at 09:55
  • @JoenTeer Hash `#` is an invalid character in JSON, you need `//` for comments because JSON is just JavaScript. Also, the code you post doesn't generate this error message. See [mcve]. – iBug Oct 01 '18 at 11:28