python common module json

python jons module

The json module mainly solves the problem of data format conversion. For example, when python receives a json object, it needs to be converted into a python object for python to process, or the python data needs to be sent to other clients. At this time, the python data needs to be converted into a json object. for other clients to operate.

json provides 4 methods, dumps loads dump load


dumps loads all deal with string objects

dump load deals with file objects

 

#1, convert python object to json object (serialization)
import json


data = {"name":"cnblogs","url":"www.cnblogs.com"}

new_data = json.dumps(data)

print(new_data)

print(type(new_data))

 





#python list convert to json
data =[1,2,3]

new_data = json.dumps(data)
print(type(data))
print(new_data)

 



#2, convert the json object to an object processed by python (deserialization)


import json
#Set a json object, you must use quotation marks here, otherwise an error will be reported!

data = '''{"name":"cnblogs","url":"www.cnblogs.com"}''' print(type(data)) new_data = json.loads(data) print(new_data) print(type(new_data))

 


#3, dump convert the python object to a json object and write it to a file

import json
data = {"name":"cnblogs","url":"www.cnblogs.com"}
with open('test.txt','w') as f:
    json.dump(data,f)

 



#4, laod reads from the file and serializes it into a python object
import json

with open('test.txt','r') as f:
    data = json.load(f)

print(data)
print (type(data))

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324955710&siteId=291194637