12 python --json

json

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

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)
View Code
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

 注意点
View Code
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'))
View Code
原文地址:https://www.cnblogs.com/the-way-to-bifk/p/7834665.html