Python json转字典字符方法实例解析
作者:天天向上327 时间:2021-06-07 11:21:40
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"
}
来源:https://www.cnblogs.com/yiwenrong/p/12664366.html
标签:Python,json,字典,字符
0
投稿
猜你喜欢
详解Python如何实现惰性导入-lazy import
2023-12-22 20:15:43
css学习笔记: css新闻列表的特殊做法
2009-07-19 14:25:00
python实现定时提取实时日志程序
2023-03-03 22:31:24
Python3.7 新特性之dataclass装饰器
2021-05-11 13:13:40
浅谈numpy广播机制
2023-08-25 22:07:51
tensorboard 可以显示graph,却不能显示scalar的解决方式
2022-07-21 08:55:46
建立MySQL数据库日常维护规范
2009-03-20 12:34:00
Python代码列表求并集,交集,差集
2021-12-03 03:33:38
python类继承用法实例分析
2022-01-25 16:44:13
分享15 超级好用得 Python 实用技巧
2023-03-01 06:42:09
Python实现微博动态图片爬取详解
2023-09-14 05:47:25
go语言beego框架web开发语法笔记示例
2024-05-21 10:25:22
浅谈终端直接执行py文件,不需要python命令
2022-12-25 14:38:11
Spring Batch读取txt文件并写入数据库的方法教程
2024-01-27 03:59:32
Python可视化神器pyecharts绘制柱状图
2021-07-26 23:05:57
关于Java中使用jdbc连接数据库中文出现乱码的问题
2024-01-28 14:57:24
你真的了解触发器么 数据实时同步更新问题剖析
2024-01-24 00:48:40
如何将自己写的模块上传到pypi
2022-06-19 10:47:06
python 并发下载器实现方法示例
2022-03-31 10:46:00
python实现mask矩阵示例(根据列表所给元素)
2022-04-19 19:37:16