json模块
JSON就是JavaScript Object Notation,这个模块完成了python对象和JSON字符串的互相转换! json是一种很多语言支持的通用语言
作用:如下,作为一个桥梁 在api接口中数据调用传输中常用
php数据类型 <----> json格式 <---> python
java数据类型 <----> json格式 <----> python
Mysql Text类型 <----> json格式 <----> python
json和python 字符类型的对比
| +-------------------+---------------+ | | Python | JSON | | +===================+===============+ | | dict | object | | +-------------------+---------------+ | | list, tuple | array | | +-------------------+---------------+ | | str, unicode | string | | +-------------------+---------------+ | | int, long, float | number | | +-------------------+---------------+ | | True | true | | +-------------------+---------------+ | | False | false | | +-------------------+---------------+ | | None | null | | +-------------------+---------------+
用途场景1:
一 、dumps函数
案例一: (案例只为演示效果)
cuizhiliangdeMacBook-Air:test cuizhiliang$ cat 1.py
#!/usr/bin/env python #encoding=utf8 import json d = {‘name‘:"张三", ‘age‘:24, ‘有病‘: False } print json.dumps(d)
结果:
cuizhiliangdeMacBook-Air:test cuizhiliang$ python 1.py {"age": 24, "\u6709\u75c5": false, "name": "\u5f20\u4e09"}
案例二: 参数的效果:
#!/usr/bin/env python #encoding=utf8 import json d = {‘name‘:"张三", ‘age‘:24, ‘有病‘: False } print json.dumps(d, ensure_ascii=False, indent=4, sort_keys=True)
结果:
{ "age": 24, "有病": false, "name": "张三" }
常用参数:
ensure_ascii 默认是True,字符编码格式
sort_keys 是否对齐
indent=4 缩进问题
二、dump 和load函数,常用在文件流读中的用途场景1 用途,就像pickle这个模块的功能一样
json dump函数 将数据已sjon格式写入文件流中
cuizhiliangdeMacBook-Air:test cuizhiliang$ cat test_json_dump.py
#!/usr/bin/env python #encoding=utf8 import json f = file(‘file.json‘, ‘w‘) d = {‘name‘:"张三", ‘age‘:24, ‘有病‘: False } json.dump(d, f, ensure_ascii=False, indent=4, sort_keys=True)
cuizhiliangdeMacBook-Air:test cuizhiliang$ python test_json_dump.py
存入文本结果:
cuizhiliangdeMacBook-Air:test cuizhiliang$ cat file.json
{
"age": 24,
"name": "张三",
"有病": false
}
区别json dumps 实现,dumps当然不是处理文件流的咯,要通过文件的write功能写入文件中
等价于:
cuizhiliangdeMacBook-Air:test cuizhiliang$ cat test_json_dumps.py
#!/usr/bin/env python #encoding=utf8 import json f = file(‘file.json‘, ‘w‘) d = {‘name‘:"张三", ‘age‘:24, ‘有病‘: False } f.write(json.dumps(d, ensure_ascii=False, indent=4, sort_keys=True))
json load 从文件流中读取json数据
cuizhiliangdeMacBook-Air:test cuizhiliang$ cat test_json_load.py
#!/usr/bin/env python # encoding: utf-8 import json f = open(‘file.json‘, ‘r‘) d = json.load(f) print type(d) print d
cuizhiliangdeMacBook-Air:test cuizhiliang$
cuizhiliangdeMacBook-Air:test cuizhiliang$ python test_json_load.py
<type ‘dict‘> {u‘age‘: 24, u‘\u6709\u75c5‘: False, u‘name‘: u‘\u5f20\u4e09‘}