json数据的处理和转化(loads/load/dump/dumps)
import requests import json url='https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&page_limit=50&page_start=0' headers={ "User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36", } response=requests.get(url) content=response.content.decode() print('content',type(content),content) # json.loads把Json格式字符串解码转换成Python对象 # 将字符串转化成字典,编码会乱 a=json.loads(content) print('json.loads',type(a),a) # json.dumps:实现python类型转化为json字符串 # 将字典转成字符串才能进行保存, a1=json.dumps(a,ensure_ascii=False) print('json.dumps',type(a1),a1) with open('static/douban.json','w',encoding='utf-8') as f: # f.write(a1) # json.dump将Python内置类型序列化为json对象后写入文件 json.dump(a1,f,ensure_ascii=False) with open('static/douban.json','r',encoding='utf-8') as r: r_dict=json.loads(r.read(),encoding='utf-8') print('r_dict',type(r_dict),r_dict) with open('static/douban2.json','w',encoding='utf-8') as f: json.dump(r_dict,f,ensure_ascii=False) # json.dump(content, f, ensure_ascii=False) # 会乱码???? # json.load读取文件中json形式的字符串元素 转化成python类型 with open('static/douban2.json','r',encoding='utf-8') as r: load_dict=json.load(r) print('load_dict',type(load_dict),load_dict)
运行结果如下: