python内置模块(json)
来源:互联网 发布:stm32f4中文数据手册 编辑:程序博客网 时间:2024/06/06 19:16
1、Json简介:
Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。
2、json类型和python数据的转换
import json# 例子1a = dict(name = 'andyfeng', age = 20, message = 'hello')print(a)print(type(a))b = json.dumps(a)print(b)print(type(b))
结果如下:
{'message': 'hello', 'age': 20, 'name': 'andyfeng'}<type 'dict'>{"message": "hello", "age": 20, "name": "andyfeng"}<type 'str'>
可以通过www.json.cn对json转换内容进行解析
{"message": "hello", "age": 20, "name": "andyfeng"}
解析后
{ "message":"hello", "age":20, "name":"andyfeng"}
3、json.loads()将json字符串解码成python对象。
在工作中,很多情况是别人给你提供的接口就是json字符串形式的。比如:你在数据库中查到的数据,返回结果是一个json的字符串的形式,这你就需要自己把这些json字符串转换成json对象。
import json# 例子1a = dict(name = 'andyfeng', age = 20, message = 'hello')print(a)print(type(a))b = json.dumps(a)print(b)print(type(b))# 例子2print('@@@@@@@@@@@@@@')#标记用c = json.loads(b)print(type(c))print(c)
结果如下:
{'message': 'hello', 'age': 20, 'name': 'andyfeng'}<type 'dict'>{"message": "hello", "age": 20, "name": "andyfeng"}<type 'str'>@@@@@@@@@@@@@@<type 'dict'>{u'message': u'hello', u'age': 20, u'name': u'andyfeng'}
说明:
通过json.loads方法把json字符串转换成python的数据字典。
4、文件和json之间的转换
#文件相关# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据#dump 就是把json数据写入到文件中# 把json写入文件中 dumpjsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’with open('a.txt', 'w')as f: json.dump(jsondata, f)
结果截图:
说明:
json.dump()可以把json数据直接写入到文件中。
5、json.load()
#文件相关# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据#dump 就是把json数据写入到文件中# 把json写入文件中 dumpjsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’with open('a.txt', 'w')as f: json.dump(jsondata, f)with open('a.txt', 'r') as fr: m = json.load(fr) print(m) print(type(m))
结果:
{"a":1, "b":2, "c":3, "d":4, "e":5}<type 'unicode'>Process finished with exit code 0
说明:
json.load()把文件内容转换成unicode数据类型返回
阅读全文
0 0
- python内置模块(json)
- python内置模块(import)
- Python内置ssl模块编程(1)
- python内置模块(loggin、os)
- python内置模块(commands、sys)
- python - 内置模块
- python内置HTMLParser模块
- python模块内置函数
- Python 内置模块1
- python 内置模块2
- python 内置模块
- python的内置模块
- Python内置模块
- Python内置模块源码查看
- Python模块的内置函数
- Python常用内置模块总结
- python pickle模块 json模块
- python模块之JSON模块
- NOIP2017 Day2_T3 列队
- 【设计模式学习笔记】单例模式
- 测试
- Android深入四大组件(六)Android8.0 根Activity启动过程(前篇)
- JAVA中关于switch方法的变更
- python内置模块(json)
- java反射详解,原理分析
- img标签,后台服务器发生变化,但是显示图片未变
- cocos2d-x屏幕自适应原理
- Easyui datagrid detailview使用简介
- 初识XSS
- Dijkstra算法求最短路径
- Java中方法的传值、重载、递归调用
- 分布式锁与实现(二)——基于ZooKeeper实现