使用 str()
处理 dict 对象后,数据是一个类似 json 但是不是 json 的str 类型。
>>> d = {"a": None, "b": "bv"}
>>> ds = str(d)
>>> print(ds)
{'a': None, 'b': 'bv'}
此时发现,键是被 单引号'
括起来的,而且如果值是None,那么转成的 str 类型,也是 None
,如果此时使用 json 解析,那么就会报错。
>>> import json
>>> json.loads(ds)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/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)
解决
使用 eval
函数处理,就可以还原为 dict 类型了
>>> type(ds) # ds 此时是字符串
<class 'str'>
>>> print(ds) # 输出内容看看
>>> dd = eval(ds) # 使用 eval 还原为 dict 对象
>>> type(dd) # 查看对象类型
<class 'dict'>
>>>