json模块就是用来处理json数据类型,主要用作网络传输。
# Python中的数据类型的格式data = [{"id": 1, "name": "武沛齐", "age": 18},{"id": 2, "name": "alex", "age": 18},('wupeiqi',123),]# JSON格式value = '[{"id": 1, "name": "武沛齐", "age": 18}, {"id": 2, "name": "alex", "age": 18},["wupeiqi",123]]'
数据类型转json被称为序列化:
import jsondata = [{"id": 1, "name": "武沛齐", "age": 18},{"id": 2, "name": "alex", "age": 18},]res = json.dumps(data)print(res) # '[{"id": 1, "name": "\u6b66\u6c9b\u9f50", "age": 18}, {"id": 2, "name": "alex", "age": 18}]'res = json.dumps(data, ensure_ascii=False)print(res) # '[{"id": 1, "name": "武沛齐", "age": 18}, {"id": 2, "name": "alex", "age": 18}]'
json类型转数据类型被称为反序列化:
import jsondata_string = '[{"id": 1, "name": "武沛齐", "age": 18}, {"id": 2, "name": "alex", "age": 18}]'data_list = json.loads(data_string)print(data_list)
python数据类型转json格式对数据类型有所要求,默认只支持dict,list,tuple,str,int,float,True,False,None
其他类型想要转换需要借助JSONEncoder才能实现
json模块常用的是:
json.dumps,序列化生成一个字符串
json.loads,发序列号生成python数据类型
json.dump,将数据序列化并写入文件
import jsondata = [{"id": 1, "name": "武沛齐", "age": 18},{"id": 2, "name": "alex", "age": 18},]file_object = open('xxx.json', mode='w', encoding='utf-8')json.dump(data, file_object)file_object.close()
json.load,读取文件中的数据并反序列化为python的数据类型
import jsonfile_object = open('xxx.json', mode='r', encoding='utf-8')data = json.load(file_object)print(data)file_object.close()
