Skip to main content
 首页 » 编程设计

python之str(dict) 和 json.dumps(dict) 的区别

2025年05月04日13powertoolsteam

str(a dictionary) 和 json.dumps(a dictionary) 的输出有什么区别?如果我打印它们,它们看起来是一样的。它们的属性(根据 dir)似乎也相同(见下文)。但我知道一定有区别。你能给我解释一下吗?

import json 
 
aDictionary= {"first": 42, "second":21} 
s = str(aDictionary) 
j = json.dumps(aDictionary) 
s == j # returns false 
dir(s) == dir(j) # returns true 

请您参考如下方法:

str(aDictionary) (以及 repr(aDictionary) )生成字典的 Python 表示。这种表示有助于调试,仅此而已。对于字典和字符串等内置类型,您将获得一种有效的 Python 语法表示。 Python 语法和 JSON 语法可能看起来相似,但不是一回事。

  • Python 对字符串文字使用单引号和双引号。 JSON 只允许双引号。
  • Python Unicode 字符串使用 \<single letter> , \xhh , \uhhhh和 \Uhhhhhhhh转义序列编码 Unicode 代码点;后一种形式用于非 BMP 代码点。 JSON 使用较小范围的 \<single letter>转义以及 \uhhhh形式,并为非 BMP 代码点编码 UTF-16 代理对(因此每个代码点有两个 \uhhhh 序列)。
  • Python 使用 None对象,JSON 使用 null作为一个特殊的“不存在”标记值。
  • Python 使用 True和 False作为 bool 值,JSON 使用 true和 false .
  • Python 字典键可以是任何可哈希类型,JSON 仅支持字符串。

所以 str(dictionary)大多数情况下,不会产生有效的 JSON 输出;仅当您的所有键和值都是 BMP 字符串且值中至少有一个单引号时,您才能最终得到一个也可以解析为有效 JSON 的文档。

就您的具体示例而言,请注意 str(aDictionary)生成一个带有单引号的文档; json.loads()无法加载此文档,因为它不是有效的 JSON:

>>> import json 
>>> aDictionary = {"first": 42, "second":21} 
>>> str(aDictionary) 
"{'first': 42, 'second': 21}" 
>>> json.loads(str(aDictionary)) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/__init__.py", line 354, in loads 
    return _default_decoder.decode(s) 
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 339, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 355, in raw_decode 
    obj, end = self.scan_once(s, idx) 
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 

切勿使用 str(pythonobject)作为序列化。虽然 ast.literal_eval() function可以从字符串表示加载合理数量的 Python 内置类型,这比使用 JSON 或更复杂的 data persistence format 慢很多如果 JSON 不符合您的需求。