JSON strings are recognized by any language, so the JSON module is an important module.
The JSON string is actually a string.
1. JSON format
The JSON format is as follows, and you must use double quotes.
2. Read the JSON file
After the JSON file is read, the data type is a string type. You can introduce a JSON module and change it to a dictionary type using Json.loads or Json.load.
Example: There is a file Products.json.
(1) with Json.loads ()
Read the file and convert the read data to a dictionary type using Json.loads ().
As you can see from the running results, the read-out res format is a string and json.loads () translates it into a dictionary format.
(2) with Json.load ()
You can see that json.load () can pass the file object directly, it will help to read the file and convert it into a dictionary format.
3. Writing to JSON file
Similarly, import the JSON module. You can use Json.dumps () or json.dump () to convert it to a JSON format and write to the file.
(1) Json.dumps ()
First use Json.dumps () to convert the dictionary into JSON format, save the User_info, and then write the User_info to the file.
Among them, Ensure_ascii=false is to ensure that Chinese is not encoded, can be displayed normally. Indent=4 refers to indentation is 4.
After running, the contents of the User_info.json file are:
(2) Json.dump ()
Json.dump () can directly manipulate the file object, the function of the implementation, the ability to directly convert the dictionary format into JSON format, and write to the file.
4. Small Exercises
Student information exists in the JSON file, requiring students to register and delete.
The contents of the Stus_info.json file are:
ImportJSONdefOp_data (filename,content=None):ifContent#If there is content, write the content to a JSON filewith open (filename,'W', encoding='Utf-8'As fw:json.dump (content, FW, Ensure_ascii=false, indent=4) Else:#If content is none, the JSON file is readWith open (filename,encoding='Utf-8') as fr:returnJson.load (FR) file_name='Stus_info.json'#Defining ConstantsAll_stus =Op_data (file_name) forIinchRange (3): Choice= Input ('1 Registration, 2 Delete, please enter:') ifchoice=='1': Username= Input ('Usenrame:') PWD= Input ('pwd:') ifUsername not inchAll_stus:all_stus[username]=pwd op_data (file_name,all_stus)Print('Congratulations,%s registration is successful! '%username)elifchoice=="2": Username= Input ('Usenrame:') All_stus.pop (username) op_data (file_name, All_stus)Print('%s deleted successfully! '%username)Else: Print('input Error, please re-enter')
Python-json Module