python json模块使用示例

来源:互联网 发布:史瓦西半径 知乎 编辑:程序博客网 时间:2024/05/05 10:55
1》简介
json:标准化(序列化)的数据格式,几乎所有语言都支持的一种数据接口格式,
在python中,json可以方便地用来序列化常规的数据类型(字典,集合,列表等),
也可以序列化类的实例等,但比较麻烦。json序列化后的数据,可读性好,人能够识别。
2》序列化到内存对象 及 从内存反序列化的两种方法:

2.1》

import jsondict={'name':'song','sex':'man'}s=json.dumps(dict)#将字典 序列化成一个内存字符串,可读性好print sprint type(s)d=json.loads(s)#从内存对象反序列化print d
2.2》

import jsondict={'name':'song','sex':'man'}s=json.JSONEncoder().encode(dict)#将字典 序列化成一个内存字符串,可读性好print sprint type(s)d=json.JSONDecoder().decode(s)#从内存对象反序列化print d
3》序列化到文件的两种方式:
3.1》

import jsondict={'name':'song','sex':'man'}#将一个对象序列化成一个字符串,并保存在文件里f=open(r'C:\Users\91135\Desktop\wahaha.json','w')print f.tell()json.dump(dict,f)#序列化dict,把结果写入指定文件中print f.tell()f.close()
3.2》

import json  d={'name':'song','sex':'man'}f=open(r'C:\Users\91135\Desktop\wahaha.json','w')print f.tell()s=json.JSONEncoder().encode(d)print s,type(s)f.write(s)print f.tell()f.close()

4》从文件反序列化的两种方式(读取json文件的两种方式):
4.1》

import json  f=open(r'C:\Users\91135\Desktop\wahaha.json','r')print f.tell()source = f.read()  print f.tell()target = json.JSONDecoder().decode(source)  print targetprint type(target)f.close()

4.2》

import json  f=open(r'C:\Users\91135\Desktop\wahaha.json','r')print f.tell()target=json.load(f)#从文件中读取数据,并反序列化成原来的数据类型print f.tell()f.close()print targetprint type(target)


(完)


1 0
原创粉丝点击