SoFunction
Updated on 2025-03-04

Example of code for reading and writing JSON files using Python

Python provides built-injsonmodule, making it very simple to read and write JSON files.

Read JSON file

To read a JSON file, you need to useopenThe 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 objectfileThe JSON data in it is parsed into a Python object.

Suggestions for use in daily development:

  • Always usewithStatements, 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 objectsdataSerialize to JSON format and write to file objectfilemiddle.ensure_ascii=FalseParameters ensure that non-ASCII characters are not escaped.indent=4Parameters format the output JSON data for easy reading.

Suggestions for use in daily development:

  • When writing to a file, use the samewithStatement.
  • useensure_ascii=FalseParameters can retain original non-ASCII characters, which is particularly important when dealing with multilingual data.
  • indentParameters 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

  1. 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")
  1. 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.

  2. Performance considerations: For very large JSON files, loading the entire file at once may result in insufficient memory. In this case, consider usingijsonlibrary to parse JSON data step by step.

  3. 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 PythonjsonModules reading and writing JSON files are basic skills in daily development.

By reasonable usewithStatements, 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 learnjsonAdvanced usage of modules, or explore third-party libraries such aspandasijsonetc. 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!