json官方说明参见:http://json.org/
Python操作json的标准api库参考:http://docs.python.org/library/json.html
重要函数
- 编码:把一个Python对象编码转换成Json字符串 json.dumps()
- 解码:把Json格式字符串解码转换成Python对象 json.loads()
>>> import json >>> info = { "name":"test", "age":"25", "sex":"man", "type":{"name1":"test1","parameter":["1","2"]} } >>> print(type(info)) <class 'dict'> >>> j = json.dumps(info) >>> print(j) {"sex": "man", "type": {"name1": "test1", "parameter": ["1", "2"]}, "age": "25", "name": "test"} >>> d = json.loads(j) >>> print(d) {'age': '25', 'type': {'name1': 'test1', 'parameter': ['1', '2']}, 'sex': 'man', 'name': 'test'} >>> print(type(d)) <class 'dict'>
sort_keys(对dict对象进行排序,我们知道默认dict是无序存放的)
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC import json data1 = {'b':789,'c':456,'a':123} data2 = {'a':123,'b':789,'c':456} d1 = json.dumps(data1,sort_keys=True) d2 = json.dumps(data2) d3 = json.dumps(data2,sort_keys=True) print(d1) print(d2) print(d3) #运行结果 {"a": 123, "b": 789, "c": 456} {"b": 789, "a": 123, "c": 456} {"a": 123, "b": 789, "c": 456}
indent 解码缩进
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC data1 = {'b':789,'c':456,'a':123} d1 = json.dumps(data1,sort_keys=True,indent=4) d2 = json.dumps(data1,sort_keys=True) print(d1) print(d2) #运行结果 { "a": 123, "b": 789, "c": 456 } {"a": 123, "b": 789, "c": 456}
用于序列化的两个模块
- json,用于字符串 和 python数据类型间进行转换
- pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load