Saturday, January 11, 2025
HomeProgrammingpython - How do I write JSON data to a file?

python – How do I write JSON data to a file?

In Python, you can write JSON data to a file using the json module. Use the json.dump() method to serialize Python objects and write them to a file.

Example:

python
import json

data = {"name": "John", "age": 30, "city": "New York"}

# Writing JSON data to a file
with open("data.json", "w") as file:
json.dump(data, file)

This code converts the data dictionary into a JSON format and saves it to data.json. You can also use the indent parameter for pretty printing:

python
json.dump(data, file, indent=4)

This approach ensures the data is correctly stored as JSON.

Previous article
Next article
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x