json编程
若是咱们要在不一样的编程语言之间传递对象,就必须把对象序列化为标准格式,好比XML,但更好的方法是序列化为JSON,由于JSON表示出来就是一个字符串,能够被全部语言读取,也能够方便地存储到磁盘或者经过网络传输。JSON不只是标准格式,而且比XML更快,并且能够直接在Web页面中读取,很是方便。json
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应以下:网络
import json dic={'name':'alvin','age':23,'sex':'male'} print(type(dic))#<class 'dict'> j=json.dumps(dic) print(type(j))#<class 'str'> f=open('序列化对象','w') f.write(j) #-------------------等价于json.dump(dic,f) f.close() #-----------------------------反序列化<br> import json f=open('序列化对象') data=json.loads(f.read())# 等价于data=json.load(f)
import json #dct="{'1':111}"#json 不认单引号 #dct=str({"1":111})#报错,由于生成的数据仍是单引号:{'one': 1} dct='{"1":"111"}' print(json.loads(dct)) #conclusion: # 不管数据是怎样建立的,只要知足json格式,就能够json.loads出来,不必定非要dumps的数据才能loads 注意点
dic={ 'name':'alex', 'age':9000, 'height':'150cm', } with open('a.txt','w') as f: f.write(str(dic)) # with open('a.txt','r') as f: # res=eval(f.read()) # print(res['name'],type(res)) # x="[null,true,false,1]" # x="[None,True,1]" # res=eval(x) # # print(res[0],type(res)) # import json # res=json.loads(x) # print(res) import json #序列化的过程:dic---->res=json.dumps(dic)---->f.write(res) dic={ 'name':'alex', 'age':9000, 'height':'150cm', } res=json.dumps(dic) print(res,type(res)) with open('a.json','w') as f: f.write(res) import json #反序列化的过程:res=f.read()---->res=json.loads(res)---->dic=res with open('a.json','r') as f: dic=json.loads(f.read()) print(dic,type(dic)) print(dic['name']) #json的便捷操做 import json dic={ 'name':'alex', 'age':9000, 'height':'150cm', } json.dump(dic,open('b.json','w'))