python之处理json

import json
# json串就是字符串
dic={
'car':{'color':'red','price':100,'count':50},
'iphone':{'color':'骚粉色','price':100,'count':50}
}

d = json.dumps(dic,indent=4,ensure_ascii=False)
#把list、字典转成json,indent多少缩进,ensure_ascii可以显示中文
file_d=open('file_d','a+',encoding='utf-8')
file_d.write(d)
print(d)

# f1 = open('f1','w',encoding='utf-8')
# json.dump(d,f1,ensure_ascii=False,indent=4)
#自动帮你写入文件,第一个参数是数据,第二个是文件对象

运行结果:

file_d = open('file_d',encoding='utf-8')
file = file_d.read()
dic_res = json.loads(file)#把json串变成python的数据类型
print(dic_res)

file_d=open('file_d',encoding='utf-8')
print(json.load(file_d))#自动帮你读文件

 运行结果:

原文地址:https://www.cnblogs.com/mpp0905/p/8299203.html