通过help(“json”) 可以参考json库使用说明
编码后的json格式字符串紧凑输出,且无顺序,其dumps方法提供一些可选的参数,让输出的格式提高可读性。
(1)sort_keys是告诉编码器按照字典key排序(a到z)输出。
>>> import json
>>> data = [{'c': 'C', 'b':(1, 6), 'a': 'A'}]
>>> print(data)
[{'a': 'A', 'c': 'C', 'b': (1, 6)}]
>>> print(json.dumps(data,sort_keys=True))
[{"a": "A", "b": [1, 6], "c": "C"}]
(2)indent参数根据数据格式缩进显示,读起来更加清晰, indent的值,代表缩进空格式:
>>> print(json.dumps(data,sort_keys=True))
[{"a": "A", "b": [1, 6], "c": "C"}]
>>> print(json.dumps(data,sort_keys=True,indent=4))
[
{
"a": "A",
"b": [
1,
6
],
"c": "C"
}
]
(3)separators参数的作用是去掉‘,’ ‘:’后面的空格,在传输数据的过程中,越精简越好,冗余的东西全部去掉。
>>> print(json.dumps(data,sort_keys=True))
[{"a": "A", "b": [1, 6], "c": "C"}]
>>> print(json.dumps(data,sort_keys=True,separators=(',',':')))
[{"a":"A","b":[1,6],"c":"C"}]
(4)skipkeys参数,在encoding过程中,dict对象的key只可以是string对象,如果是其他类型,那么在编码过程中就会抛出ValueError的异常。skipkeys可以跳过那些非string对象当作key的处理.
>>> data2 = [{"a": "A", "b": [1,6], "c": "C", ('d',): 'D'}]
>>> print(json.dumps(data2,sort_keys=True,separators=(',',':')))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib64/python2.6/json/encoder.py", line 367, in encode
chunks = list(self.iterencode(o))
File "/usr/lib64/python2.6/json/encoder.py", line 306, in _iterencode
for chunk in self._iterencode_list(o, markers):
File "/usr/lib64/python2.6/json/encoder.py", line 204, in _iterencode_list
for chunk in self._iterencode(value, markers):
File "/usr/lib64/python2.6/json/encoder.py", line 309, in _iterencode
for chunk in self._iterencode_dict(o, markers):
File "/usr/lib64/python2.6/json/encoder.py", line 268, in _iterencode_dict
raise TypeError("key {0!r} is not a string".format(key))
TypeError: key ('d',) is not a string
>>> print(json.dumps(data2,sort_keys=True,skipkeys=True))
[{"a": "A", "b": [1, 6], "c": "C"}]
(5)输出真正的中文需要指定ensure_ascii=False
如果无任何配置,或者说使用默认配置,
输出的会是‘凉凉’的ASCII字符吗,而不是真正的中文。
这是因为json.dumps 序列化时对中文默认使用的ascii编码。
>>> print(json.dumps('中国'))
"\u4e2d\u56fd"
>>> print(json.dumps('中国',ensure_ascii=False))
"中国"
网友评论