[英]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.由于 Python 2 API 似乎一团糟 - 从文件系统函数我有时会得到 unicode 字符串,有时会得到标准字符串 - 我现在正在尝试从 Python 2 过渡到 Python 3。但是在这样做时我遇到了关于
json
模块的问题.
I run a standard Ubuntu system with Python 3.4.我使用 Python 3.4 运行标准的 Ubuntu 系统。 When I try to use the JSON module I get the following error message:
当我尝试使用 JSON 模块时,我收到以下错误消息:
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.乍一看,这似乎是 Python 3 的 JSON 模块中的一个错误。我简直不敢相信,因为我没有做任何与众不同的事情:我只是阅读了一个非常非常简单的 JSON 配置文件。
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. Python 2 中
json.load
的第二个参数是encoding
,但是在 Python 3 中第二个参数是cls
并且它必须是None
(默认)或JSONDecoder
子类。 The signature of json.load
is now json.load
的签名是现在
json.load(fp, cls=None, ...)
You need to remove 'utf-8'
from the list of arguments (pass it to the file opener instead).您需要从参数列表中删除
'utf-8'
(改为将其传递给文件打开器)。
OTOH json.loads
still has the encoding
argument, but it "is ignored and deprecated". OTOH
json.loads
仍然有encoding
参数,但它“被忽略和弃用”。
json.load()
in Python 3 does not accept binary files and therefore the 2nd parameter encoding
is removed. Python 3中的
json.load()
不接受二进制文件,因此删除了第二个参数encoding
。
'utf-8'
is interpreted as cls
parameter here that is unrelated to the encoding that leads to the TypeError
that you see. 'utf-8'
在这里被解释为cls
参数,它与导致您看到的TypeError
的编码无关。 Drop 'utf-8'
from the json.load()
call -- you should pass the encoding to the code that opens the file instead:从
json.load()
调用中删除'utf-8'
——您应该将编码传递给打开文件的代码:
import json
with open('text.json', encoding='utf-8') as file:
data = json.load(file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.