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)
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!