python json与字典对象互相转换

改文章转自:https://www.cnblogs.com/Lin-Yi/p/7640147.html

 

 

 1 import requests
 2 import json
 3 '''
 4 json.loads(json_str) json字符串转换成字典
 5 json.dumps(dict) 字典转换成json字符串 
 6 
 7 '''
 8 # 这是一个ajax发起的get请求,获取一个json对象
 9 r = requests.get("https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items?os=ios&for_mobile=1&start=0&count=18&loc_id=108288&_=0")
10 json_response = r.content.decode()  # 获取r的文本 就是一个json字符串
11 
12 # 将json字符串转换成dic字典对象
13 dict_json = json.loads(json_response)
14 print(type(dict_json))
15 
16 # 将字典转换成json字符串
17 str_json = json.dumps( dict_json )
18 print(type(str_json))
19 
20 # 字典转换成json 存入本地文件
21 with open('./a.txt','w') as f:
22     # 设置不转换成ascii  json字符串首缩进
23     f.write( json.dumps( dict_json,ensure_ascii=False,indent=2 ) )
复制代码
posted @ 2018-04-09 17:51  长白山  阅读(85317)  评论(0编辑  收藏  举报