首页 > 技术文章 > json模块

baiby 2019-04-19 17:38 原文

 1 import json
 2 
 3 #存在文件里面的东西,读出来都是字符串
 4 
 5 #json是一个字符串
 6 
 7 #1.打开文件
 8 #2.把字典dumps转成字符串
 9 #3.把字符串写到文件里面
10 
11 :字典的形式写入文件
12 d = {'baibai':'123456','yaya':'3454325'}
13 #1.json.dumps,把字典转换成字符串
14 res = json.dumps(d) #把字典转换成json串
15 print(type(res))
16 f = open('users3.txt','w')
17 f.write(res)
18 运行结果:文件内容展示:{"baibai": "123456", "yaya": "3454325"}
19 
20 ==================================================================
21 #1.打开文件
22 #2.读取文件内容
23 #3.json.loads把读到的字符串转换成字典
24 
25 f = open('users3.txt')
26 res = f.read()
27 print('res的类型',res,type(res))
28 d = json.loads(res) #把json串转成字典
29 print('d..',d,type(d))
30 运行结果:res的类型 {"baibai": "123456", "yaya": "3454325"} <class 'str'>
31 d.. {'baibai': '123456', 'yaya': '3454325'} <class 'dict'>
32 
33 ====================================================================
34 d = {'baibai':'123456','yaya':'3454325','对对对对':'fdfd'}
35                                          #转换格式的
36 res = json.dumps(d,indent=4,ensure_ascii=False) #把字典转换成json串
37 print(type(res))
38 f = open('users3.txt','w',encoding='utf-8')
39 f.write(res)
40 运行结果:
41 {
42     "baibai": "123456",
43     "yaya": "3454325",
44     "对对对对": "fdfd"
45 }
46 
47 ============================================================================
48 注:dumps 和 loads  与  dump 和 load 的区别是带s的是与字符串相关的,所以才可以进行调整格式什么的,不带s的 是直接操作文件的,不需要读的那一步,本身就可以去读取文件。
49 =============================================================================
50 
51 #1.打开文件
52 #2.load
53 f = open('users3.txt',encoding='utf-8')
54 res = json.load(f)
55 print(res)
56 运行结果:{'baibai': '123456', 'yaya': '3454325', '对对对对': 'fdfd'}
57 
58 ===========================================================================
59 
60 # 1.打开文件
61 # 2.json.dump 写入
62 d = {'baibai':'123456','yaya':'3454325','对对对对':'fdfd'}
63 f = open('users4.json','w',encoding='utf-8')
64 json.dump(d,f,indent=4,ensure_ascii=False)
65 
66 运行结果:
67 {
68     "baibai": "123456",
69     "yaya": "3454325",
70     "对对对对": "fdfd"
71 }
72 注:后缀改成 .json是为了文件内容格式好看 有颜色

 

推荐阅读