1 import json
2 # python的数据类型转成json
3 # 字典转字符串
4 d = {"code":0,"msg":"操作成功","token":"XXXX"}
5 # print(d)
6 # json_str = json.dump(d,ensure_ascii=False)
7 # print(json_str) #不加ensure_ascii=False 就是Unicode
8
9 # json转成python的数据类型
10 # json_str = '{"code":0,"msg":"操作成功","token":"XXXX"}'
11 # dict = json.loads(json_str)
12 # print(dict)
13
14 with open("student.txt",encoding="utf-8") as f:
15 new_file = json.loads(f.read()) #由json串转为其它数据类型
16 print(new_file)
17 #
18 # d = {"code":"0","msg":"操作成功","token":"XXXX"}
19 # # with open("student.txt",'w+',encoding="utf-8") as f:
20 # # new_file = json.dumps(d,ensure_ascii=False,indent=4) #indent缩进
21 # # f.write(new_file)
22
23 # 只操作文件的
24 # json.load()
25 # json.dump()
26
27 # with open("student.txt",encoding="utf-8") as f:
28 # new_file = json.load(f) #
29 # print(new_file)
30 #
31 # with open("student.txt",encoding="utf-8") as f:
32 # new_file = json.dump(d,f)
33
34 # d = {"code":"0","msg":"操作成功","token":"XXXX"}
35 def wirte(d):
36 with open("student.txt",'w+',encoding="utf-8") as f:
37 f.write(json.dumps(d,ensure_ascii=False,indent=4)) #indent缩进
38
39 d = {"code":"0","msg":"操作成功1","token":"XXXX"}
40 wirte(d)