How can I Python write JSON to file from a dictionary?
I have JSON data stored in a dictionary and I want to write it to a file.
Here’s my current approach:
f = open('data.json', 'wb')
f.write(data)
However, I get the error:
TypeError:
must be string or buffer, not dict
Hey Mate,
You can try my method of resolving your query:
Using json.dump()
: The json module provides a method called dump()
that can directly serialize a dictionary into a JSON formatted string and write it to a file.
import json
data = {"name": "John", "age": 30, "city": "New York"}
with open('data.json', 'w') as f:
json.dump(data, f)
This approach automatically converts the dictionary into a JSON string and writes it to the file in the correct format.
Hope this helps
You can first convert the dictionary into a JSON string using json.dumps()
and then write that string to a file manually.
import json
data = {"name": "John", "age": 30, "city": "New York"}
json_data = json.dumps(data)
with open('data.json', 'w') as f:
f.write(json_data)
This allows you to handle the conversion explicitly and then perform the file operation.
Handling binary mode with json.dump(): If you need to open the file in binary mode (‘wb’), you can convert the dictionary to a JSON string and then encode it to a byte format before writing.
import json
data = {"name": "John", "age": 30, "city": "New York"}
with open('data.json', 'wb') as f:
json.dump(data, f)
However, using binary mode (‘wb’) is unnecessary unless you’re handling data that needs to be in binary format, such as when working with non-text files. For normal JSON operations, text mode (‘w’) is recommended.