Python jons Module
JSON module is mainly to solve the problem of conversion of data format, such as Python received a JSON object needs to be converted to Python object, for Python processing, or Python data need to be sent to other clients, At this point, you need to convert the Python data to a JSON object for other clients to manipulate.
JSON provides 4 methods, dumps loads dump load
Dumps loads handles all string objects.
Dump load handles the file object
#1, convert a Python object to a JSON object (serialized)
Import Jsondata = {"Name": "Cnblogs", "url": "www.cnblogs.com"}new_data = json.dumps (data) print (new_data) print (Type ( New_data))
#python列表转换为json
Data =[1,2,3]new_data = json.dumps (data) print (type (data)) print (New_data)
#2, convert the JSON object to a Python-processed object (deserialization)
Import JSON
#定一个json对象, you must use quotation marks here, or you will get an error!
data = ' ' {' name ': ' cnblogs ', ' url ': ' www.cnblogs.com '} ' ' Print (type ') New_data = json.loads (data) print (New_data) Print (Type (new_data))
#3, dump converts the Python object to a JSON object and writes the file
Import Jsondata = {"Name": "Cnblogs", "url": "Www.cnblogs.com"}with Open (' Test.txt ', ' W ') as F: Json.dump (DATA,F)
#4, Laod is read from the file and serialized into a Python object
Import Jsonwith Open (' Test.txt ', ' R ') as F: data = Json.load (f) print (data) print (type data)
Python Common module JSON