Python json轉(zhuǎn)字典字符方法實例解析
josn基本操作
1.導(dǎo)入import json
2.字典轉(zhuǎn)json:json.dumps(dict,ensure_ascii=False),加,ensure_ascii=False轉(zhuǎn)換之后無中文亂碼
3.json轉(zhuǎn)字典:json.loads(str)
4.json轉(zhuǎn)字典: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)
#字典轉(zhuǎn)json,因為python沒json類型所以str表示
def dict_json(self):
d = {"name":"張三","age":18}
j = json.dumps(d,ensure_ascii=False)
print('dict_json函數(shù):類型:',type(d),'轉(zhuǎn)類型',type(j),'\n',j)
#json轉(zhuǎn)字典
def json_dict(self):
s = '{"name":"張三","age":18}'
d = json.loads(s)
print('json_dict函數(shù):類型:',type(s),'轉(zhuǎn)類型',type(d))
#接口調(diào)用直接返回 字典(dict)
def get_json(self):
d = self.geturl.json()
print('get_json函數(shù)類型:',type(d))
#接口調(diào)用直接返回字符串
def get_str(self):
s = self.geturl.text
print('get_str函數(shù)返回類型:',type(s))
if __name__=="__main__":
js = jsonC()
js.dict_json()
js.json_dict()
js.get_json()
js.get_str()
運行結(jié)果
dict_json函數(shù):類型: <class 'dict'> 轉(zhuǎn)類型 <class 'str'>
{"name": "張三", "age": 18}
json_dict函數(shù):類型: <class 'str'> 轉(zhuǎn)類型 <class 'dict'>
get_json函數(shù)類型: <class 'dict'>
get_str函數(shù)返回類型: <class 'str'>
調(diào)用get例子
http://wthrcdn.etouch.cn/weather_mini?city=北京
返回json值:
{"data":
{"yesterday":
{"date":"28日星期六","high":"高溫 30℃","fx":"西南風(fēng)","low":"低溫 17℃","fl":"<![CDATA[<3級]]>","type":"晴"},
"city":"北京","forecast":
[
{"date":"29日星期天","high":"高溫 29℃","fengli":"<![CDATA[<3級]]>","low":"低溫 18℃","fengxiang":"南風(fēng)","type":"晴"},
{"date":"30日星期一","high":"高溫 28℃","fengli":"<![CDATA[<3級]]>","low":"低溫 19℃","fengxiang":"南風(fēng)","type":"晴"},
{"date":"1日星期二","high":"高溫 29℃","fengli":"<![CDATA[<3級]]>","low":"低溫 20℃","fengxiang":"南風(fēng)","type":"多云"},
{"date":"2日星期三","high":"高溫 29℃","fengli":"<![CDATA[<3級]]>","low":"低溫 17℃","fengxiang":"南風(fēng)","type":"晴"},
{"date":"3日星期四","high":"高溫 30℃","fengli":"<![CDATA[<3級]]>","low":"低溫 12℃","fengxiang":"東南風(fēng)","type":"多云"}
],"ganmao":"各項氣象條件適宜,無明顯降溫過程,發(fā)生感冒機率較低。","wendu":"29"
},"status":1000,"desc":"OK"
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
用不到50行的Python代碼構(gòu)建最小的區(qū)塊鏈
這篇文章主要為大家詳細介紹了用不到50行的Python代碼構(gòu)建最小的區(qū)塊鏈,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
jupyter notebook 實現(xiàn)matplotlib圖動態(tài)刷新
這篇文章主要介紹了jupyter notebook 實現(xiàn)matplotlib圖動態(tài)刷新,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python使用多線程+socket實現(xiàn)端口掃描
這篇文章主要為大家詳細介紹了python使用多線程+socket實現(xiàn)端口掃描,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05

