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
Release: 2024-12-26 20:15:16
Original
937 people have browsed it

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)
Copy after login

you might encounter the error:

TypeError: must be string or buffer, not dict
Copy after login

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)
Copy after login

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)
Copy after login
  • 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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template