简体   繁体   中英

JSON library exception in Python 3

As the Python 2 API seems to be messed up - from file system functions I sometimes get unicode strings, sometimes standard strings - I am now attempting a transition from Python 2 to Python 3. But while doing so I run into problems regarding the json module.

I run a standard Ubuntu system with Python 3.4. When I try to use the JSON module I get the following error message:

Traceback (most recent call last):
  File "./sysmon.py", line 227, in <module>
    jsonCfgObj = json.load(json_file, 'utf-8', strict = False)
  File "/usr/lib/python3.4/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.4/json/__init__.py", line 331, in loads
    return cls(**kw).decode(s)
TypeError: 'str' object is not callable

At first glance this seems to be a bug in the JSON module of Python 3. Something I can hardly believe because I don't do anything which would be out of the ordinary: I just read a very very simple JSON configuration file.

Do you have any ideas how to deal with this error?

The second argument of json.load in Python 2 was encoding , however in Python 3 the second argument is cls and it must be None (the default) or JSONDecoder subclass. The signature of json.load is now

json.load(fp, cls=None, ...)

You need to remove 'utf-8' from the list of arguments (pass it to the file opener instead).


OTOH json.loads still has the encoding argument, but it "is ignored and deprecated".

json.load() in Python 3 does not accept binary files and therefore the 2nd parameter encoding is removed.

'utf-8' is interpreted as cls parameter here that is unrelated to the encoding that leads to the TypeError that you see. Drop 'utf-8' from the json.load() call -- you should pass the encoding to the code that opens the file instead:

import json

with open('text.json', encoding='utf-8') as file:
    data = json.load(file)

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