json序列化和反序列化

 1 #json序列化和反序列化
 2 '''
 3 info = {
 4     'name': 'AxiBa',
 5     'sex': 'male'
 6 }
 7 f = open('test.txt', 'a', encoding="utf-8")
 8 f.write(str(info))
 9 f.close()
10 '''
11 import json
12 info = {
13     'name': 'AxiBa',
14     'sex': 'male'
15 }
16 f = open('test.txt', 'a', encoding="utf-8")
17 f.write(json.dumps(info))
18 f.close()
19 #反序列化
20 '''
21 f = open("test.txt", "r", encoding="utf-8")
22 res = f.read()
23 # print(res['name']) #报错 字符串索引必须是整数
24 res = eval(res) #解析
25 print(res['name']) #成功
26 f.close()
27 '''
28 import json
29 f = open("test.txt", "r", encoding="utf-8")
30 res = json.loads(f.read())
31 print(res['name']) #成功
32 f.close()

 

posted @ 2017-06-20 15:20  Bird_getUpEarly  阅读(176)  评论(0编辑  收藏  举报