JSON is actually a string representation of a Python dictionary, but a dictionary cannot be passed directly as a complex object, so it needs to be converted to a string. The process of conversion is also a serialization process.
Serialize to JSON string format with Json.dumps
>>>ImportJson>>>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 ']})>>>Printjdict{"Connection": ["Keep-alive"],"Host": ["127.0.0.1:5000"],"Cache-control": ["Max-age=0"]}
Although DiC and jdict print the same strings, the actual types are different. DiC is a dictionary type and jdict is a string type
<type ‘dict‘>type(jdic)type(jdict)<type ‘str‘>
You can use the Json.dumps serialization list as a JSON string format
>>> list = [14325>>> jlist = json.dumps(list)>>> print jlist[14325]
The list and jlist types are also different
type(list)<type ‘list‘>type(jlist)<type ‘str‘>
Json.dumps has the following various parameters
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 sort
>>> 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"}
Format alignment
>>> print json.dumps({‘4‘5‘6‘7}, sort_keys=True, indent=4){ "4"5, "6"7}
Specify delimiter
json.dumps([1,2,3,{‘4‘: 5, ‘6‘: 7}], separators=(‘,‘,‘:‘))‘[1,2,3,{"4":5,"6":7}]‘
Serializing to a file object with Json.dump
>>> json.dump({‘4‘5‘6‘7open(‘savejson.txt‘‘w‘printopen(‘savejson.txt‘).readlines()[‘{"4": 5, "6": 7}‘]
The Json.dump parameter is similar to 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 to deserialize a JSON string into a Python object
The function signature is:
json.loadscls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Note that the "s" here must be a string that is deserialized after the Unicode character
>>> dobj = json.loads(‘{"name":"aaa", "age":18}‘)>>> ‘dict‘>>>> print dobj{u‘age‘18u‘name‘u‘aaa‘}
Json.load deserializing from a file into a Python object
The signature is:
json.loadcls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Instance:
>>> fobj = json.load(open(‘savejson.txt‘))>>> print fobj{u‘4‘5u‘6‘7}>>> ‘dict‘>
Python's JSON module