How do I Python write JSON to file? I have JSON data stored in a dictionary, and I want to write it to a file. I tried the following:
f = open('data.json', 'wb')
f.write(data)
But I encountered the error:
TypeError: must be string or buffer, not dict
How can I correctly write the dictionary data to a JSON file?
Hey All, I’ve worked with Python a lot, and I often get asked how to write a Python dictionary to a JSON file. It’s pretty straightforward. You can use the json
module, which comes pre-installed with Python.
Exactly, @ian-partridge! To elaborate, if you prefer to convert the dictionary to a JSON string first and then write it to a file, you can use json.dumps()
to serialize the dictionary and then write()
to save it. Here’s a quick example of how you can do it:
import json
data = {"name": "Alice", "age": 30}
with open('data.json', 'w') as f:
f.write(json.dumps(data))
This is how you can python write json to file
by serializing the dictionary first. But, there’s another way to do this which is a bit more efficient.
Yes, @ian-partridge! Another approach, and one that I personally prefer for readability, is to use json.dump()
directly, which avoids the need for dumps()
. Plus, if you want to make the output more readable, you can add the indent
parameter for pretty printing. Here’s how you can do it:
import json
data = {"name": "Alice", "age": 30}
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
This will write the dictionary into the file with a clean, indented format, making the JSON easier to read and understand. It’s perfect when you want to python write json to file
and make sure it’s not just functional but also clean for debugging or sharing.