python学习笔记5--json处理

import json

#json串就是字符串。

d = {
    'car':{'color':'red','price':100,'count':50},
    'bus':{'color':'red','price':100,'count':50},
    'phone':{'color':'red','price':100,'count':50},
    'ipad':{'color':'red','price':100,'count':50},
     }



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

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

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


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

 

posted @ 2018-04-25 19:39  可可的私房菜  阅读(193)  评论(0编辑  收藏  举报