时间:2021-07-01 10:21:17 帮助过:33人阅读
用json.dumps序列化为json字符串格式
>>> 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序列化到文件对象中
>>> 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把json字符串反序列化为python对象
函数签名为:
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从文件中反序列化为python对象
签名为:
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'>
更多Python json模块使用实例相关文章请关注PHP中文网!