![](/img/trans.png)
[英]how to convert all int to str in a nested dict with json.dumps()?
[英]difference between str(dict) and json.dumps(dict)
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语法可能看起来相似,但不是同一回事 。
\\<single letter>
, \\xhh
, \\uhhhh
和\\Uhhhhhhhh
转义序列来编码的Unicode代码点; 后一种形式用于非BMP代码点。 JSON使用较小范围的\\<single letter>
转义\\uhhhh
和\\uhhhh
形式,并为非BMP代码点编码UTF-16代理对(因此每个代码点有两个\\uhhhh
序列)。 None
对象,JSON使用null
来作为特殊的“不存在”哨兵值。 True
和False
作为布尔值,JSON使用true
和false
。 所以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()
函数可以从字符串表示形式加载合理数量的Python内置类型,但比起将JSON用于同一作业要慢得多,如果不适合JSON,则它要比复杂的数据持久性格式慢得多。您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.