How does python read and write json data?
This example shares the code for reading and writing json data in python for your reference. The details are as follows:
Case:
In web applications, json data is often used for data transmission. In essence, dictionary-type data is converted into strings, which are used for webpage transmission. Then, the received strings are converted into dictionary-like data.
Requirements:Converts dictionaries to strings, converts strings to Dictionary data types, and writes data to files.
How to do it?
1. Identify the differences between dumps and dump. The dump interface is a file that is directly written into the file. dumps converts the corresponding data type to a string. The opposite is true for loads and dumps, load directly reads the file from the file and converts the data to the corresponding data type
2. convert data first, and use a string as an intermediate Bridge
#! /Usr/bin/python3 import json def w_json (data): # Write the json file to the file with open ('json _ test. json ', 'w') as wf: json. dump (data, wf) print ('OK') def r_json (): # Read the json file with open ('json _ test. json ', 'R') as rf: data = json. load (rf) return data def chage_data (data): # convert json data. try: # separators removes spaces before and after the corresponding symbol, which is transmitted over the network, space is meaningless # sort_keys can also be used to sort by dictionary. The dictionary is valid and the return json format is generally used for network transmission. dumps (data, separators = [',', ':'], sort_keys = True) except t Exception as e: print (e) return None if _ name _ = '_ main _': d = {'xiao _ ming': 18, 'xiao _ er': 50, 'xiao _ san': 17, '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 data: ', r_data)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.