Python自动化运维Python入门到精通

Python基础021--json序列化和反序列化

2018-03-05  本文已影响6人  不一样的丶我们

json序列化和反序列化

# json的序列化
In [61]: dict2 = {'name':'zzzz','age':33,'address':'郑州市'}
In [62]: print(type(dict2))
<type 'dict'>
In [63]: print(dict2)
{'age': 33, 'name': 'zzzz', 'address': '\xe9\x83\x91\xe5\xb7\x9e\xe5\xb8\x82'}
In [65]: dict2_xu = json.dumps(dict2,ensure_ascii=False)
In [66]: print(type(dict2_xu))
<type 'str'>
In [67]: print(dict2_xu)
{"age": 33, "name": "zzzz", "address": "郑州市"}

# json的反序列化
In [10]: #coding:utf-8
In [11]: import json
In [12]: dict3 = {'name':'zzz','age':22,'address':'郑州市'}
In [13]: print(type(dict3))
<type 'dict'>
In [14]: print(dict3)
{'age': 22, 'name': 'zzz', 'address': '\xe9\x83\x91\xe5\xb7\x9e\xe5\xb8\x82'}
In [15]: dict3_xu = json.dumps(dict3,ensure_ascii=False)
In [16]: print(type(dict3_xu))
<type 'str'>
In [17]: print(dict3_xu)
{"age": 22, "name": "zzz", "address": "郑州市"}
In [18]: dict3_fan = json.loads(dict3_xu)
In [19]: print(type(dict3_fan))
<type 'dict'>
In [20]: print(dict3_fan)
{u'age': 22, u'name': u'zzz', u'address': u'\u90d1\u5dde\u5e02'}



# 把文件内容进行序列化和反序列化
# 序列化-->1、先把列表序列化成字符串,然后写入到文件中再进行读取
In [27]: import json
In [28]: list1 = ['Apple','Hwawei','selenium','java','python']
In [29]: json_xu = json.dumps(list1)
In [30]: type(json_xu)
Out[30]: str
In [31]: file1 = open('./ccc.txt','w+')
In [32]: file1.write(json_xu)
In [33]: file1.tell()
Out[33]: 49
In [34]: file1.seek(0)
In [35]: file1.read()
Out[35]: '["Apple", "Hwawei", "selenium", "java", "python"]'
# 反序列化--->2、先读取文件中的字符串,然后再反序列成列表
# loads方法中的参数是string在打开文件时要使用read()方法
In [43]: json_fan = json.loads(open('./ccc.txt','r').read()) 
In [44]: print json_fan
[u'Apple', u'Hwawei', u'selenium', u'java', u'python']
In [45]: type(json_fan)
Out[45]: list
# 反序列化的标准写法
# load是基于文件操作的方法
In [46]: json_fan = json.load(open('./ccc.txt','r'))
In [47]: type(json_fan)
Out[47]: list


# dump和load对文件进行序列化和反序列化                      --->推荐使用对文件的操作方法
In [49]: import json
In [50]: list2 = ['zzzz','aaaa','bbbb']
In [51]: json.dump(list2,open('./aaa.txt','w'))             # 把序列化后的列表写入文件中
In [52]: json_fan = json.load(open('./aaa.txt','r'))        # 从文件中读取反序列化后的列表
In [53]: print(json_fan)
[u'zzzz', u'aaaa', u'bbbb']
In [54]: print(type(json_fan))
<type 'list'>

方法 描述
json.dump 基于文件操作的序列方法
json.dumps 基于字符串操作的序列方法,在操作文件的时候没有读取功能,要用到read()
json.load 基于文件操作的反序列方法
json.loads 基于字符串操作的反序列方法,在操作文件的时候没有读取功能,要用到read()
上一篇 下一篇

猜你喜欢

热点阅读