Python provides built-injson
module, making it very simple to read and write JSON files.
Read JSON file
To read a JSON file, you need to useopen
The function opens the file and then usesMethod parses the file contents into Python objects.
import json # Open and read the JSON filewith open('', 'r', encoding='utf-8') as file: data = (file) # Print the read dataprint(data)
Code sample description:
-
open('', 'r', encoding='utf-8')
: Open in read-only mode with nameand specify the encoding as UTF-8.
-
(file)
: Put the file objectfile
The JSON data in it is parsed into a Python object.
Suggestions for use in daily development:
- Always use
with
Statements, this ensures that the file is automatically closed after use, avoiding resource leakage. - Specifies the encoding format of the file, usually using UTF-8, to ensure that data containing non-ASCII characters can be processed correctly.
Write to JSON file
To write Python objects to a JSON file, you can usemethod.
import json # Data to be writtendata = { "name": "Alice", "age": 30, "city": "New York" } # Write data to JSON filewith open('', 'w', encoding='utf-8') as file: (data, file, ensure_ascii=False, indent=4)
Code sample description:
-
(data, file, ensure_ascii=False, indent=4)
: Convert Python objectsdata
Serialize to JSON format and write to file objectfile
middle.ensure_ascii=False
Parameters ensure that non-ASCII characters are not escaped.indent=4
Parameters format the output JSON data for easy reading.
Suggestions for use in daily development:
- When writing to a file, use the same
with
Statement. - use
ensure_ascii=False
Parameters can retain original non-ASCII characters, which is particularly important when dealing with multilingual data. -
indent
Parameters can improve the readability of JSON files, but in production environments, this parameter is usually omitted to reduce file size.
Points to note in actual development
- Exception handling: When reading or writing a file, you may encounter IO errors or other exceptions. You should use the try-except block to catch and handle these exceptions.
import json try: with open('', 'r', encoding='utf-8') as file: data = (file) except FileNotFoundError: print("file not found") except : print("JSON parsing error")
Data Verification: Before processing JSON data, you should verify that the data is formatted correctly, especially in production environments, incorrect JSON data may cause the program to crash.
Performance considerations: For very large JSON files, loading the entire file at once may result in insufficient memory. In this case, consider using
ijson
library to parse JSON data step by step.Security: When processing JSON data from untrusted sources, you should be careful to prevent JSON injection attacks. Ensure that the input data is properly cleaned and verified.
Summarize
Using Pythonjson
Modules reading and writing JSON files are basic skills in daily development.
By reasonable usewith
Statements, specifying the correct encoding format, handling exceptions, verifying data, and considering performance and security issues, can effectively handle JSON data and avoid potential problems.
In actual development, JSON data is usually used in various scenarios such as configuration files, API responses, logging, etc.
Mastering these basic operations can help developers process data more efficiently and improve the robustness and maintainability of their code.
In addition, for more complex JSON data processing requirements, such as the parsing of nested structures, processing of large data volumes, etc., we can further learnjson
Advanced usage of modules, or explore third-party libraries such aspandas
、ijson
etc. to meet specific needs.
Through the above detailed instructions and code examples, I hope that the interviewer can fully understand how to process JSON files in Python and apply this knowledge in actual work.
This is the end of this article about code examples for using Python to read and write JSON files. For more related Python to read and write JSON content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!