简体   繁体   中英

Python json.load(file) error with valid JSON

I have a question concerning an issue I ran into while using the json lib in Python.

I'm tying to read a json file using the json.load(file) command using the following code:

import json

filename= '../Data/exampleFile.json'
histFile= open(filename, 'w+')
print(json.load(histFile))

The JSON file I am trying to read is valid according to some website I found: a screenshot of that validation, because I'm new and still lack the reputation...

The error message I'm getting is the following:

File ".\testLoad.py", line 5, in <module>
print(json.load(histFile))
File "C:\Users\...\Python\Python37\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\...\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\...\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\...\Python\Python37\lib\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)

Alright, so I believe it is not the file that is the issue, but the json.load(file) works for me in other cases.

Sadly I was not able to figure this error-message out on my own, so it would be amazing if someone with some more experience dealing with Python-JSON interaction could maybe help me out.

You opened the file for writing :

histFile= open(filename, 'w+')
#                        ^^^^

The w mode first truncates the file, so the file is empty (it doesn't matter here that the file can also be read from, the + sees to that but the file is truncated nonetheless). See the open() function documentation :

'w' : open for writing, truncating the file first)

There is no JSON data in it to parse. This is why the exception tells you that parsing failed at the very start of the file:

Expecting value: line 1 column 1 (char 0)

There is no data in line one, column one.

If you wanted to open a file for both reading and writing without truncating it first, use 'r+' as the file mode.

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