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
>>> 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 "]}
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 = [1, 4, 3, 2, 5] >>> jlist = json.dumps (list) >>> print jlist[1, 4, 3, 2, 5]
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 ': 7}, open (' Savejson.txt ', ' W ')) >>> print open (' 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.loads (s[, encoding[, cls[, 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": +} ') >>> type (dobj) <type ' dict ' >>>> Print Dobj{u ' age ': +, U ' name ': U ' aaa '}
Json.load deserializing from a file into a Python object
The signature is:
Json.load (fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]] [] ]]])
Instance:
>>> fobj = json.load (open (' Savejson.txt ')) >>> print Fobj{u ' 4 ': 5, U ' 6 ': 7}>>> type (fobj) < Type ' dict ' >