您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了Python如何實現json轉字典字符,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
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函數:類型: <class 'dict'> 轉類型 <class 'str'>
{"name": "張三", "age": 18}
json_dict函數:類型: <class 'str'> 轉類型 <class 'dict'>
get_json函數類型: <class 'dict'>
get_str函數返回類型: <class '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如何實現json轉字典字符的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。