编程语言
首页 > 编程语言> > 四、python josn转字典转字符

四、python josn转字典转字符

作者:互联网

目录

josn

举例说明

#!/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'>
{"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"
}

标签:get,python,josn,json,dict,类型,type,self,字典
来源: https://www.cnblogs.com/yiwenrong/p/12658112.html