Case:
JSON data is often used in Web applications to transfer data, essentially converting a dictionary type of data into a string, transmitting a Web page through a string, and then converting the received string into a dictionary-like data
requirement : Implement dictionary into string, convert string to dictionary data type, write file
How to do?
- Clear the difference between dumps and dump, dump interface is a file, write directly to the file, dumps the corresponding data type into a string, loads and dumps instead, load directly from the file to read the file and convert the data to the corresponding data type
- Data conversion First, string as intermediate bridge
#!/usr/bin/python3import jsondef W_json (data): # Write JSON file to file with open (' Json_test.json ', ' W ') as WF: Json.dump (data, WF) print (' OK ') def R_json (): # reads the JSON file with open (' Json_test.json ', ' R ') as RF: data = json.load (RF) return datadef chage_data (data): # for JSON data conversion try: # Separators will remove the space before and after the corresponding symbol, In the network transmission, the space is meaningless # can also be sorted by the dictionary by Sort_keys, the dictionary is valid, the network transmission is generally used in JSON data format return json.dumps (data, separators=[', ', ' : '], sort_keys=true) except Exception as E: print (e) return None if __name__ = = ' __main__ ': D = {' xiao_ming ': +, ' xiao_er ': +, ' Xiao_san ': +, ' Xu_xue ': None, ' b_l ': True} # d = [8, 2, 2, 7, 0, None, true]
data = Chage_data (d) if data: W_json (data) R_data = R_json () print (' read: ', r_data)
Pythhon_ How to read JSON data