json的读写方式与Python和字典与json的相互转化
一. python与json对象
1.json定义[python内置]
json:javascript原生的对象。(不需要第三方解析,由浏览器自动进行解析)
2.json对象的定义
jsonobj = {dict};
3.json组件的引入:import json
4.json与dict相互转换
e.g:
import json
#初始化字典
dict = {'A':1,'B':2,'C':3}
print(type(dict))#查看类型
print(dict['B'])
print(dict['C'])
#将字典对象转为json字符串:dumps(dict,ensure_ascii = False)
jsonstr = json.dumps(dict)
print(type(jsonstr))#查看类型
print(jsonstr)
#将json字符串转为字典:
jstr = jsonstr#定义json字符串
print(type(jstr))#查看类型
dict1 = json.loads(jstr,encoding='utf-8')#转为字典
print(type(dict1))#查看类型
print(dict1['A'],dict1['B'])
注:ensure_ascii = False 表示中文不用转为utf-8的字符编码
indent:多行缩进空格数
5.将dict对象转为字符串对象并存储到文件中
#with open("file_name",'w',encoding='utf-8') as f:
# json.dump(dict_,f,indent=2,ensure_ascii=False)#写文件为多行
import json
import os
dict = {'A':1,'B':2,'C':3}
with open("file_name",'w',encoding='utf-8') as f:
json.dump(dict,f,indent=2,ensure_ascii=False)
6.从文件读取json字符串并转为python字典的方法
import json
import os
dict = {}
with open("filename.json",encoding='utf-8') as f:
dict = json.load(f)
print(dict['A'])
print(type(dict))