【Python】学习笔记4-json模块

1、先引入json模块,json其实就是字符串

  import json

2、不使用json模块,读写字典到问题,需要用str()

 1 d = {
 2     'car':{
 3         'color':'red',
 4         'price':100,
 5         'count':50
 6     },
 7     'bus':{
 8         'color':'red',
 9         'price':100,
10         'count':50
11     }
12 }
13 f = open('f1','w',encoding='utf-8')
14 f.write(str(d))

3、利用json模块,读写数组/字典到文件

dumps()或dump()来实现将字典/list写入文件中
 1 #   dumps()字典/list转字符串
 2 d = {
 3     'car':{
 4         'color':'红色',
 5         'price':100,
 6         'count':50
 7     },
 8     'bus':{
 9         'color':'red',
10         'price':100,
11         'count':50
12     }
13 }
14 s = [1,3,4]
15 res = json.dumps(d,indent=4,ensure_ascii = False)  # 把字典/list转成json字符串,indent是缩进的值,使输出标准化,ensure_ascii = False中文
16 res = json.dumps(s,indent=4,ensure_ascii = False)  # 把字典/list转成json字符串,indent是缩进的值,使输出标准化,ensure_ascii = False中文
17 f1 = open('f1','w',encoding='utf-8')
18 f1.write(res)
19 
20 # 上面代码等价于下面
21 #  dump()字典/list转字符串,直接写入文件,第一个参数是数据,第二个是文件对象,
22 # f1 = open('f1','w',encoding='utf-8')
23 # res = json.dump(d,f1,indent = 4,ensure_ascii = False)
从文件中读取json,loads(),load()字符串转字典/list
1 #loads()特别注意:json串在文件中,必须是双引号,才能正常转换,否则3中会报错
2 # f1 = open('f1','r',encoding='utf-8')
3 # print(json.loads(f1.read())) # 字典类型res = {'car': {'color': '红色', 'price': 100, 'count': 50}, 'bus': {'color': 'red', 'price': 100, 'count': 50}}
4 
5 #或者load(),自动帮你读文件,与上面无异
6 f1 = open('f1','r',encoding='utf-8')
7 print(json.load(f1))#如果是字典返回字典,如果是数组返回数组

 

posted @ 2018-01-18 20:27  萌_CALY  阅读(154)  评论(0编辑  收藏  举报