Python-json模块的基本使用

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))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值