处理json

1、处理json:

import json
#json串就是字符串
d = {
    'cha':{'color':'red','price':100,'count':150},
    '苹果':{'color':'red','price':100,'count':150},
}
res = json.dumps(d,indent=4,ensure_ascii=False)  #把字典转换成json串,indent缩进,ensure_ascii=False显示中文
f1 = open('f1.txt','w',encoding='utf-8')
f1.write(res)
print(res)

f1 = open('f1.txt',encoding='utf-8')
res = f1.read()
dict_res = json.loads(res)    # 把json变成python数据类型,loads操作字符串
print(type(dict_res))

f1 = open('f1.txt','w',encoding='utf-8')
json.dump(d,f1,ensure_ascii=False,indent=4)
#自动写入文件,d为参数数据,f1为文件对象

f1 = open('f1.txt',encoding='utf-8')
print(json.load(f1))     #load读文件
#自动读文件
原文地址:https://www.cnblogs.com/wang-hao-yue/p/8303236.html