Concept
serialization (serialization): Converts the state information of an object into a process that can be stored or transmitted over a network, in the form of JSON, XML, and so on. Deserialization is the state of the deserialized object that is read from the storage area (Json,xml) and re-created.
JSON (JavaScript Object Notation): A lightweight data interchange format that is easier to read and write than XML, is easy to parse and generate, and JSON is a subset of JavaScript.
Python2.6 started adding JSON modules without additional download, and the Python JSON module serialization and deserialization process is encoding and decoding , respectively.
encoding: Converts a Python object encoding into a JSON string
decoding: Converting JSON format string decoding to Python object
For simple data types (string, Unicode, int, float, list, tuple, dict), they can be processed directly.
The conversion control is as follows:
650) this.width=650; "title=" image "src=" http://images.cnblogs.com/cnblogs_com/coser/201112/201112141621131652. PNG "alt=" image "Width=" 244 "height=" "border=" 0 "style=" border:0px;margin:0px;padding:0px; "/>
The type conversions from JSON to Python are compared as follows:
650) this.width=650; "title=" image "src=" http://images.cnblogs.com/cnblogs_com/coser/201112/201112141621146178. PNG "alt=" image "Width=" 244 "height=" 213 "border=" 0 "style=" border:0px;margin:0px;padding:0px; "/>
Direct attached code:
# coding: utf-8# filename: testjsonimport json# python data to JSON string obj = [[1,2,3],123,123.123, ' abc ', {' key1 ':(), ' key2 ':(4,5,6)}] # sort_keys is to tell the encoder to sort by dictionary (A to Z) the output # indent parameter is indented according to the data format and is read more clearly. The function of the # separators parameter is to remove,: the trailing space, In the process of transmitting data, the more streamlined the better, the redundant things are all removed encodejson = json.dumps (obj, sort_keys=true,indent=4,separators= (', ', ': ') # str () generally converts a value into a string. # repr () is to turn an object into a string display, note that it is only displayed with, Print repr (obj) Print encodejson# json string to Pythonstrjson = r ' [[1, 2, 3], 123, 123.123, "abc", {"Key2": [4, 5, 6 ], "Key1": [1, 2, 3]}] ' Decodejson = json.loads (Strjson) # Decodejson for listprint ' decodejson[0]: ', decodejson[0]print ' decodejson[1]: ', decodejson[1] The For val in decodejson: print val# load () and dump () methods can be implemented to write files, and read file F = open ("T.json", ' w+ ') f.seek (0) JSON. Dump (obj, f) #f. Write (Encodejson) F.flush () #注: To refer back to the file start position f.seek (0) print json.load (f)
Python processing JSON