Home >Backend Development >Python Tutorial >How to Write Python Dictionaries as JSON to a File?

How to Write Python Dictionaries as JSON to a File?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 21:40:13371browse

How to Write Python Dictionaries as JSON to a File?

Writing JSON Data to a File

When attempting to write JSON data stored in a dictionary to a file, an error may occur, stating that the data must be a string or buffer. This arises because dictionaries are not directly compatible with JSON format.

Solution:

To write JSON data to a file, it must first be encoded as JSON. This can be achieved using the json module in Python:

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

This code opens a file named 'data.json' in write mode and uses the json.dump() function to write the JSON-encoded data to the file.

For broader compatibility across Python 2 and 3 and non-ASCII characters:

import json
with open('data.json', 'w') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

The ensure_ascii=False parameter prevents ASCII-only output, while the indent=4 parameter adds indentation for readability.

Refer to the JSON documentation for further details and customization options.

The above is the detailed content of How to Write Python Dictionaries as JSON to a File?. 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