python json module dumps, dump, loads, load function describes

Json module dumps, loads, dump, load function describes

 

1, json.dumps ()
for the type of data into dict str
2, json.loads ()
for the type of data into str dict
. 3, The json.dump () for the type of data into dict str, and written to the json file. The following two methods can be written to the data file json
4, json.load () for reading data from a file json

Test code is as follows:

. 1  Import JSON
 2  
. 3  
. 4 data_str = ' { "name": "Benben", "age": 18, "sex": " F"} ' 
. 5  
. 6  # The type of data into str dict 
. 7 str_to_dict = JSON. loads (data_str, encoding = ' UTF-. 8 ' )
 . 8  
. 9  Print ( " type data_str as: {} " .format (type (data_str)))
 10  Print ( " type str_to_dict as: {} " .format (type (str_to_dict)))
 . 11  
12 is  # a dict type data into STR 
13 is= json.dumps dict_to_str (str_to_dict, ensure_ascii = False)
 14  Print ( " type dict_to_str as: {} " .format (type (dict_to_str)))
 15  
16  # The dict type data into str, and written into json file 
. 17 with Open ( " test_json.json " , MODE = ' W ' , encoding = ' UTF-. 8 ' ) AS FP:
 18 is      the json.dump (str_to_dict, FP)
 . 19  
20 is  # read data from json file 
21 is with Open ( " test_json.json " , MODE = ' R & lt ', Encoding = ' UTF-. 8 ' ) AS FP:
 22 is      load_dict = the json.load (FP)
 23 is      Print ( " data read-out is: {} " .format (load_dict))

Results are as follows:

data_str types are: < class  ' STR ' > 
type str_to_dict as: < class  ' dict ' > 
type dict_to_str as: < class  ' STR ' > 
the read data is: { ' name ' : ' benben ' , ' Age ' : 18 is, ' Sex ' : ' F ' }

 

Guess you like

Origin www.cnblogs.com/benben-wu/p/11278446.html