Python Forum
json.load() in Python 3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: json.load() in Python 3 (/thread-15044.html)



json.load() in Python 3 - jazmad - Dec-31-2018

Hi

I'm trying to adapt some code I've found online for use in my own function. I can get the code to run in Python 2 but would really like to get it to work in Python 3.

The code that works in Python 2 is:
for ID in id_list:
        try:
                with open(location + ID+ '.json','r') as f:
                        data = json.load(f)
To run in Python 3, I've tried changing it to (the files are utf-8 encoded):
for ID in id_list:
        try:
                with open(location + ID+ '.json',encoding = 'utf-8') as f:
                        data = json.load(f)
This worked for another occasion where the .json files had ANSI encoding but here I get the error:
Error:
Traceback (most recent call last): File "<ipython-input-24-e1396ed76a2e>", line 1, in <module> runfile('...', wdir='...') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "...", line 166, in <module> X2 = function(X) File "...", line 110, in Function data = json.load(f) File "C:\ProgramData\Anaconda3\lib\json\__init__.py", line 296, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\ProgramData\Anaconda3\lib\json\__init__.py", line 348, in loads return _default_decoder.decode(s) File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value
Any help why this isn't working?

Thanks!


RE: json.load() in Python 3 - Larz60+ - Dec-31-2018

try (using f-string (if your python 3.6 or newer)):
for id in id_list:
    with open(f'location{id}') as fp:
        data = json.load(fp)
if using python 3 older than 3.6 use:
for id in id_list:
    with open(f'location{}'.format(id)) as fp:
        data = json.load(fp)
FYI: please use 4 space indentation