How do I write JSON data to a file in Python?

I have JSON data stored in a dictionary, and I want to write it to a file. I tried the following approach:

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

However, this results in the error:

TypeError: must be string or buffer, not dict

How can I correctly save the JSON data to a file in Python?

To write a Python dictionary to a JSON file, you need to first encode the dictionary as JSON before writing. Here’s the recommended approach for maximum compatibility (both Python 2 and 3):

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

For modern systems using Python 3 and UTF-8 support, you can use the following method to ensure better formatting:
import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

You can refer to the JSON documentation for more details on encoding options.

If you want to write the JSON string directly, you can use json.dumps to convert the dictionary to a JSON-formatted string before writing it to the file:

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

If you prefer to use pathlib for better path handling:

from pathlib import Path
import json
path = Path('data.json')
with path.open('w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)