31、序列化:
1、json实现序列化,json.dumps()和json.loads()。
>>> s1 = {'k1':'v1','k2':'v2'}
>>> import json
>>> json.dumps(s1)
'{"k1": "v1", "k2": "v2"}'
>>> s2 = json.dumps(s1)
>>> type(s2)
<class 'str'>
>>> json.loads(s2)
{'k1': 'v1', 'k2': 'v2'}
>>> type(json.loads(s2))
<class 'dict'>
2、注意:反序列化时要用双引号“”才行。
#1:>>> dic1 = "{'key1':'v1','key2':'v2'}"
>>> ret2 = json.loads(dic1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python3/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/local/python3/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python3/lib/python3.5/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)
#2:>>> dic2 = "["alex","xiao"]" 都用双引号“”也会报错。
File "<stdin>", line 1
dic2 = "["alex","xiao"]"
^
SyntaxError: invalid syntax
>>> dic2 = '["alex","xiao"]' 可以
3、 dump()和load()的使用
>>> l1 = [11,22,33]
>>> json.dump(l1,open('/opt/a.txt','w'))
[root@bogon opt]# cat a.txt
[11, 22, 33]
>>> l2 = json.load(open("/opt/a.txt","r"))
>>> print(l2,type(l2))
[11, 22, 33] <class 'list'>