python3中json模块的用法

 1 __author__ = "JentZhang"
 2 
 3 import json
 4 
 5 user_info = {"id": 1000, "name": "zhangsan", "age": 25, "address": "xxxxxxxxxx", "mobile": "15966148787"}
 6 
 7 # 将字典转换为JSON字符串
 8 json_str = json.dumps(user_info)
 9 print(json_str)
10 print(type(json_str))
11 
12 # 将JSON字符串转换为字典
13 str_json = '{"name":"zhangsan","age":20}'
14 json_obj = json.loads(str_json)
15 print(json_obj)
16 print(type(json_obj))
17 
18 f = open('json_file','w')
19 dic = {'k1':'v1','k2':'v2','k3':'v3'}
20 json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
21 f.close()
22 
23 f = open('json_file')
24 dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
25 f.close()
26 print(type(dic2),dic2)

 

posted on 2018-11-30 14:45  JentZhang  阅读(703)  评论(0编辑  收藏  举报