注意:

  • json中的字符串都是双引号引起来的
    • 如果不是双引号
      • eval:能实现简单的字符串和python类型的转化
      • replace:把单引号替换为双引号
  • 往一个文件中写入多个json串,不再是一个json串,不能直接读取
    • 一行写一个json串,按照行来读取

找到返回json的url

json数据提取

示例:loads、dumps

url = "https://m.douban.com/rexxar/api/v2/recommend_feed?alt=json&next_date=2019-02-11&loc_id=108288&gender=&birthday=&udid=9fcefbf2acf1dfc991054ac40ca5114be7cd092f&for_mobile=1"
html_str = requests.get(url).text
# json.loads把json字符串转化为python类型
ret1 = json.loads(html_str)
# 普通输出
#print(ret1)
# 美化输出
#pprint(ret1)
# json.dumps把python类型转化为json字符串
with open('example.json','w',encoding='utf-8') as f:
    # 参数 ensure_ascii默认为True,即使用asic编码格式,设置为False即可显示中文 
    # 参数 indent 代表每个缩进缩进几个字符
    f.write(json.dumps(ret1,ensure_ascii=False,indent=4))

# 运行结果
# 文件内容
{
    "msg": "invalid_request_1284",
    "code": 1287,
    "request": "GET /rexxar/v2/recommend_feed",
    "localized_message": ""
}

示例:json.load、json.dump

# 使用json.load提取类文件对象中的数据
with open('example.json','r',encoding='utf-8')as f:
    ret4 = json.load(f)
    print(ret4)
    print(type(ret4))

# 运行结果
{'msg': 'invalid_request_1284', 'code': 1287, 'request': 'GET /rexxar/v2/recommend_feed', 'localized_message': ''}
<class 'dict'>

# json.dump能够把python类型放入类文件对象中
with open('example.json','w',encoding='utf-8')as f:
    json.dump(ret1,f,ensure_ascii=False,indent=2)

发表回复