실제로 JSON은 Python 사전의 문자열 표현이지만 복잡한 객체이므로 사전을 직접 전송할 수 없으므로 변환 과정도 직렬화 과정입니다. 🎜>
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"]}
<type 'dict'> >>> type(jdic) >>> type(jdict) <type 'str'>
>>> list = [1, 4, 3, 2, 5] >>> jlist = json.dumps(list) >>> print jlist [1, 4, 3, 2, 5]
>>> type(list) <type 'list'> >>> type(jlist) <type 'str'>
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)
>>> 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(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]]]]]]]])
>>> 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'>