Python json轉(zhuǎn)字典字符方法實(shí)例解析
josn基本操作
1.導(dǎo)入import json
2.字典轉(zhuǎn)json:json.dumps(dict,ensure_ascii=False),加,ensure_ascii=False轉(zhuǎn)換之后無(wú)中文亂碼
3.json轉(zhuǎn)字典:json.loads(str)
4.json轉(zhuǎn)字典:requests.get().josn()
5.返回字符串: requests.get().text
舉例源碼
#!/usr/bin/python3# encoding:utf-8import jsonimport requestsclass jsonC(): def __init__(self): self.url = ’http://wthrcdn.etouch.cn/weather_mini?city=北京’ self.geturl = requests.get(self.url) #字典轉(zhuǎn)json,因?yàn)閜ython沒(méi)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()
運(yùn)行結(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級(jí)]]>','type':'晴'},'city':'北京','forecast':[{'date':'29日星期天','high':'高溫 29℃','fengli':'<![CDATA[<3級(jí)]]>','low':'低溫 18℃','fengxiang':'南風(fēng)','type':'晴'},{'date':'30日星期一','high':'高溫 28℃','fengli':'<![CDATA[<3級(jí)]]>','low':'低溫 19℃','fengxiang':'南風(fēng)','type':'晴'},{'date':'1日星期二','high':'高溫 29℃','fengli':'<![CDATA[<3級(jí)]]>','low':'低溫 20℃','fengxiang':'南風(fēng)','type':'多云'},{'date':'2日星期三','high':'高溫 29℃','fengli':'<![CDATA[<3級(jí)]]>','low':'低溫 17℃','fengxiang':'南風(fēng)','type':'晴'},{'date':'3日星期四','high':'高溫 30℃','fengli':'<![CDATA[<3級(jí)]]>','low':'低溫 12℃','fengxiang':'東南風(fēng)','type':'多云'}],'ganmao':'各項(xiàng)氣象條件適宜,無(wú)明顯降溫過(guò)程,發(fā)生感冒機(jī)率較低。','wendu':'29'},'status':1000,'desc':'OK'}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML在語(yǔ)音合成中的應(yīng)用2. jscript與vbscript 操作XML元素屬性的代碼3. 不要在HTML中濫用div4. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過(guò)程和條件語(yǔ)句)7. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)8. XML入門的常見(jiàn)問(wèn)題(三)9. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)10. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說(shuō)明(學(xué)習(xí))
