from request的简单封装 import MyRequest
import json
from pprint import pprint
testUrl = "https://movie.douban.com/j/search_subjects?type=tv&tag=%E7%83%AD%E9%97%A8&page_limit=10&page_start=0"
myRequest = MyRequest()
content = myRequest.send_parse_url(testUrl)
print("没有解析的字符串信息->> {}".format(content))
print(type(content))
json_content = json.loads(content)
print("解析为json格式后的数据->> {}".format(json_content))
print(type(json_content))
print("格式化打印json数据为->>")
pprint(json_content)
print("==" * 50)
print("解析成一定格式 并输出到文本中")
"""
json.loads() json.dumps() 方法的使用
loads 方法可以把json字符串转换成json对象
dumps 方法可以把python中的json对象转换成json字符串
loads dumps 方法可以对json对象 str数据 进行直接操作
"""
# 确保输出编码格式为utf-8
with open("temp_file/douban.json", mode="w+", encoding="utf-8") as f:
# 解析python 中的json对象数据 为json格式的str
# 默认会把字符转换成 ascii码 但是为了方便观看 可以取消,取消后输出到文件中的中文就是正常的了
# 如果json格式数据没有缩进 整个数据是一行 如果为了方便阅读 可以使用indent 来进行缩进 正常情况缩进2个空格就合适
json_dumps = json.dumps(json_content, ensure_ascii=False, indent=2)
f.write(json_dumps)
"""
json.load() json.dump() 方法的使用
不加s 的方法只适用于 具有read() write() 方法的类对象 典型的就是open(xx,"w") 的对象文件
load 方法把open(xxxx) 对象文件加载出来
dump 方法把json数据 加载到open(xxxx)对象文件中去
"""
print("**" * 50)
"""
加载文件对象
"""
# 需要注意这里的文件读写模式为 读写模式
with open("temp_file/douban2.json", "r", encoding="utf-8") as f:
json_load = json.load(f)
print(json_load)
print(type(json_load))
print("_+" * 50)
"""
输出文件对象
"""
with open("temp_file/douban3.json", "w+", encoding="utf-8") as f:
json.dump(json_content, f, ensure_ascii=False, indent=2)
print("输出文件对象完成->>{}".format(json_content))
Python-json模块的基本使用
最新推荐文章于 2024-02-27 00:16:59 发布