Tatsächlich ist JSON die String-Darstellung eines Python-Wörterbuchs, aber als komplexes Objekt kann das Wörterbuch nicht direkt übertragen werden, daher muss es in eine String-Form konvertiert werden 🎜>
Verwenden Sie json.dumps, um in das JSON-String-Format zu serialisieren>>> 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'>