实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接传递,所以需要将其转换成字符串形式.转换的过程也是一种序列化过程.
>>> import json
>>> dic {‘Connection‘: [‘keep-alive‘], ‘Host‘: [‘127.0.0.1:5000‘], ‘Cache-Control‘: [‘max-age=0‘]}
>>> jdict = json.dumps({‘Connection‘: [‘keep-alive‘], ‘Host‘: [‘127.0.0.1:5000‘], ‘Cache-Control‘: [‘max-age=0‘]})
>>> print jdict
{"Connection": ["keep-alive"], "Host": ["127.0.0.1:5000"], "Cache-Control": ["max-age=0"]}
虽然dic和jdict打印的字符串是相同的,但是实际它们的类型是不一样的.dic是字典类型,jdict是字符串类型
<type ‘dict‘>
>>> type(jdic)
>>> type(jdict)
<type ‘str‘>
可以用json.dumps序列化列表为json字符串格式
>>> list = [1, 4, 3, 2, 5]
>>> jlist = json.dumps(list)
>>> print jlist
[1, 4, 3, 2, 5]
list和jlist类型同样是不一样的
>>> type(list)
<type ‘list‘>
>>> type(jlist)
<type ‘str‘>
json.dumps有如下多种参数
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
key排序
>>> print json.dumps({1:‘a‘, 4:‘b‘, 3:‘c‘, 2:‘d‘, 5:‘f‘},sort_keys=True)
{"1": "a", "2": "d", "3": "c", "4": "b", "5": "f"}
格式对齐
>>> print json.dumps({‘4‘: 5, ‘6‘: 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
指定分隔符
>>> json.dumps([1,2,3,{‘4‘: 5, ‘6‘: 7}], separators=(‘,‘,‘:‘))
‘[1,2,3,{"4":5,"6":7}]‘
>>> json.dump({‘4‘: 5, ‘6‘: 7}, open(‘savejson.txt‘, ‘w‘))
>>> print open(‘savejson.txt‘).readlines()
[‘{"4": 5, "6": 7}‘]
json.dump参数和json.dumps类似
json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
函数签名为:
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
注意这里的”s”必须是字符串,反序列化后为unicode字符
>>> dobj = json.loads(‘{"name":"aaa", "age":18}‘)
>>> type(dobj)
<type ‘dict‘>
>>> print dobj
{u‘age‘: 18, u‘name‘: u‘aaa‘}
签名为:
json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
实例:
>>> fobj = json.load(open(‘savejson.txt‘))
>>> print fobj
{u‘4‘: 5, u‘6‘: 7}
>>> type(fobj)
<type ‘dict‘>
原文地址:http://blog.csdn.net/csujiangyu/article/details/44947243