Home >Backend Development >Python Tutorial >How Can I Correctly Write JSON Data from a Dictionary to a File in Python?

How Can I Correctly Write JSON Data from a Dictionary to a File in Python?

DDD
DDDOriginal
2024-12-26 20:15:16949browse

How Can I Correctly Write JSON Data from a Dictionary to a File in Python?

How to Write JSON Data to a File

When attempting to write JSON data stored in a dictionary to a file using the code:

f = open('data.json', 'wb')
f.write(data)

you might encounter the error:

TypeError: must be string or buffer, not dict

This is because the data in the dictionary needs to be encoded as JSON before writing.

Using Python Built-in JSON Module:

Python's built-in json module provides a convenient way to encode and decode JSON data. To write JSON data from a dictionary, you can use the following code:

For maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

For modern systems (Python 3 and UTF-8 support):

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)
  • ensure_ascii=False: This ensures that non-ASCII characters are not converted to escape sequences, preserving the original characters.
  • indent=4: This indents the JSON output for readability.

Note: For more information on the json module, refer to the Python documentation.

The above is the detailed content of How Can I Correctly Write JSON Data from a Dictionary to a File in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn