Python_json类方法
import requests
import json
headers = {
"User-Agent": "Mozilla/5.0 (Linux Android 6.0Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Mobile Safari/537.36"
}
url = "https://m.toutiao.com/list/?tag=__all__&max_time=0&min_behot_time=0&ac=wap&count=20&format=json_raw&_signature=zDO00gAAr-RscdJ0dNc1tswztM&i=&as=A196A32E19BD4E3&cp=63E95DB45E63CE1&aid=1698"
response = requests.get(url, headers=headers)
j = response.content.decode()
# json.loads把json字符串转成称python类型
ret1 = json.loads(j)
print(type(ret1)) # <class 'dict'>
# json.dumps 能把python字典转换称json字符串
# ret2 = json.dumps(ret1)
# print(type(ret2)) # <class 'str'>
with open("jinritoutiao.json", "w", encoding="utf-8") as f:
# ensure_ascii:这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
# indent:缩进字符
f.write(json.dumps(ret1, ensure_ascii=False, indent=4))
# 提取json字符串中的新闻摘要,输出到txt中
with open("result.txt", "w", encoding="utf-8") as f:
for i in range(15):
f.write("第{}条: {}\n".format(i+1, ret1["data"][i]["abstract"]))
# json.load and json.dump
# 具有read或者write方法的对象就是类文件对象
# 读取json的类文件对象
with open("./jinritoutiao.json", "r", encoding="utf-8") as f:
print(json.load(f))
# 写入json的类文件对象
with open("./jinritoutiao1.json", "w", encoding="utf-8") as f:
json.dump(ret1, f, ensure_ascii=False, indent=4)
标签:encoding,Python,方法,ret1,dumps,json,ensure,ascii
From: https://www.cnblogs.com/thankcat/p/17117812.html