Python 中 的 json 模块
python 中的json 模板主要的两个功能:序列化和反序列化序列化: encoding 将python 数据 编码成json 字符串
对应的函数有 dump 和 dumps
反序列化: decoding将json 字符串 解码成 python 数据
对应的函数有 load 和 loads
json 序列化 dumps 实例:
Base example
>>> import json
>>> data=['foo', {'bar': ('baz', None, 1.0, 2)}]
>>> print data
['foo', {'bar': ('baz', None, 1.0, 2)}]
>>> json_data=json.dumps(data)
>>> print json_data
["foo", {"bar": ["baz", null, 1.0, 2]}]
>>>
Compact encoding(压缩编码)
>>> import json
>>> data =
>>> print data
>>> data_json = json.dumps(data)
>>> print data_json
>>> data_json2 = json.dumps(data,sort_keys=True)
>>> print data_json2
>>> data_json2 = json.dumps(data,sort_keys=True,separators=(',',':'))
>>> print data_json2
参数 separators 将 , 和 : 后门的空格剔除掉了。 separators 的值必须是一个 tuple
帮助中的英文注释:
If specified, separators should be a (item_separator, key_separator) tuple.
The default is (', ', ': ').To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
Pretty printing(一种格式化输出)
>>> data_json3 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'))
>>> print data_json3
[
1,
2,
3,
{
"4":5,
"6":7
}
]
indent 会让每个键值对显示的时候,以缩进几个字符对齐。以方便查看
帮助中的英文注释:
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level.An indent level of 0 will only insert newlines.None is the most compact representation.Since the default item separator is ', ',the output might include trailing whitespace when indent is specified.You can use separators=(',', ': ') to avoid this.
josn 反序列化 loads 实例:
>>> obj = }]
>>> str_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> obj2 = json.loads(str_json)
>>> print obj2
}]
>>> obj2 == obj
True
大数据处理:
以上不论时序列化的dumps 和 反序列化的loads 。所针对的数据都是一个json 字符串 或者时 一个python 的数据结构。那么当遇到了大量的json数据(如一个json 的配置文件)
或者 将一个python 的数据结构导出成一个json 的配置文件。
#! /usr/bin/env python
# _*_ encoding: utf-8 _*_
import json
# dump example
data = [{'lang':('python','java'),'school':"beijing"},"God"]
f = open('test.json','w+')
json.dump(data,f)
f.flush()
f.close()
# load example
fd = file("test.json")
js = json.load(fd)
print js
奇淫巧计:
python 的 json 结合 shell 输出
$ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
页:
[1]