Talk about the deserialization of load and loads in python

  • 2021-12-09 09:27:51
  • OfStack

load and loads

Introduction:

In python automation, we pass 1 parameters that need to be read from the file, and the dictionary read from is not python object data type but string type.

In this way, when we pass the parameters, the format will be incorrect, and load will be used to realize deserialization

python object data types include list, dict, tuple, set, and so on

Case 1: load

load: load deals primarily with file streams

First, we create a new txt file, and write a dictionary in the file

{"a":"1","b":"2"}

At this time, we read him out with py file


f = open(r'C:\Users\ Zhang Tianci \PycharmProjects\pythonProject\test\lianxi\load.txt','r',encoding='utf-8') # Pass open Open the newly created txt Document 
a = f.read()   # Read f All the contents under the file 
print(a)  # Print what is read under 
print(type(a)) # Format of reading content under printing 

Return results

D:\ software\ python.exe C:/Users/Zhang Tianci/PycharmProjects/pythonProject/test/lianxi/111. py
{"a":"1","b":"2"}
< class 'str' >

It can be seen that what we read looks like a dictionary, but the actual type type is str type. If the interface needs to be transmitted when doing interface test,

json format data, at this time, an error will be reported.

Solution: Use load mode to convert the data in the file into dict dictionary format in python object


import json
f = open(r'C:\Users\ Zhang Tianci \PycharmProjects\pythonProject\test\lianxi\load.txt','r',encoding='utf-8') # Pass open Open the newly created txt Document 
a = json.load(f)  # Read f All the contents under the file 
print(a)  # Print what is read under 
print(type(a)) # Format of reading content under printing 

Return results

D:\ software\ python. exe C:/Users/Zhang Tianci/PycharmProjects/pythonProject/test/lianxi/111. py
{'a': '1', 'b': '2'}
< class 'dict' >

Case 2: loads

loads: loads deals primarily with character streams

Print a dictionary in the form of 1 character normally, and return the result of str type


test = "{'a':'1','b':'2'}"
print(test)
print(type(test))

Return results

{'a':'1','b':'2'}
< class 'str' >

To convert an sting type to an python readable object using loads


import json
test = '{"a":"1","b":"2"}'
test1 = json.loads(test)
print(test1)
print(type(test1))

Return results

{'a': '1', 'b': '2'}
< class 'dict' >


Related articles: