首页 > python爬虫

Python json转字典字符方法实例解析

时间:2020-07-20 python爬虫 查看: 862

josn基本操作

1.导入import json

2.字典转json:json.dumps(dict,ensure_ascii=False),加,ensure_ascii=False转换之后无中文乱码

3.json转字典:json.loads(str)

4.json转字典:requests.get().josn()

5.返回字符串: requests.get().text

举例源码

#!/usr/bin/python3
# encoding:utf-8
import json
import requests

class jsonC():
  def __init__(self):
    self.url = 'http://wthrcdn.etouch.cn/weather_mini?city=北京'
    self.geturl = requests.get(self.url)

  #字典转json,因为python没json类型所以str表示
  def dict_json(self):
    d = {"name":"张三","age":18}
    j = json.dumps(d,ensure_ascii=False)
    print('dict_json函数:类型:',type(d),'转类型',type(j),'\n',j)

  #json转字典  
  def json_dict(self):
    s = '{"name":"张三","age":18}'
    d = json.loads(s)
    print('json_dict函数:类型:',type(s),'转类型',type(d))

  #接口调用直接返回 字典(dict) 
  def get_json(self):
    d = self.geturl.json()
    print('get_json函数类型:',type(d))

  #接口调用直接返回字符串  
  def get_str(self):
    s = self.geturl.text
    print('get_str函数返回类型:',type(s))

if __name__=="__main__":
  js = jsonC()
  js.dict_json()
  js.json_dict()
  js.get_json()
  js.get_str()

运行结果

dict_json函数:类型: 转类型
{"name": "张三", "age": 18}
json_dict函数:类型: 转类型
get_json函数类型:
get_str函数返回类型:

调用get例子

http://wthrcdn.etouch.cn/weather_mini?city=北京

返回json值:

{"data":
{"yesterday":
{"date":"28日星期六","high":"高温 30℃","fx":"西南风","low":"低温 17℃","fl":"<![CDATA[<3级]]>","type":"晴"},
"city":"北京","forecast":
[
{"date":"29日星期天","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 18℃","fengxiang":"南风","type":"晴"},
{"date":"30日星期一","high":"高温 28℃","fengli":"<![CDATA[<3级]]>","low":"低温 19℃","fengxiang":"南风","type":"晴"},
{"date":"1日星期二","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 20℃","fengxiang":"南风","type":"多云"},
{"date":"2日星期三","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 17℃","fengxiang":"南风","type":"晴"},
{"date":"3日星期四","high":"高温 30℃","fengli":"<![CDATA[<3级]]>","low":"低温 12℃","fengxiang":"东南风","type":"多云"}
],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒机率较低。","wendu":"29"
},"status":1000,"desc":"OK"
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

展开全文
上一篇:Python unittest框架操作实例解析
下一篇:windows上彻底删除jupyter notebook的实现
输入字:
相关知识
Python爬虫基础之爬虫的分类知识总结

来给大家讲python爬虫的基础啦,首先我们从爬虫的分类开始讲起,下文有非常详细的知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下

Python爬虫基础讲解之请求

今天带大家了解一下python爬虫的基础知识,文中有非常详细的解释说明,对正在学习python爬虫的小伙伴们有很好地帮助,需要的朋友可以参考下

PyQt5爬取12306车票信息程序的实现

12306是学习爬虫的比较好的一个练手网站。本文主要实现了PyQt5爬取12306车票信息程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python爬虫之m3u8文件里提取小视频的正确姿势

本文给大家分享如何正确提取m3u8文件里的.ts视频,并合成完整的.mp4格式视频,通过图文实例代码的形式给大家介绍的非常详细,对Python提取m3u8文件小视频感兴趣的朋友一起看看吧