1. 程式人生 > 程式設計 >Python json轉字典字元方法例項解析

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":"南風",{"date":"30日星期一","high":"高溫 28℃","low":"低溫 19℃",{"date":"1日星期二","low":"低溫 20℃","type":"多雲"},{"date":"2日星期三",{"date":"3日星期四","low":"低溫 12℃","fengxiang":"東南風","type":"多雲"}
		],"ganmao":"各項氣象條件適宜,無明顯降溫過程,發生感冒機率較低。","wendu":"29"
	},"status":1000,"desc":"OK"
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。