Categories
Python Answers

How to write JSON data to a file with Python?

Spread the love

Sometimes, we want to write JSON data to a file with Python.

In this article, we’ll look at how to write JSON data to a file with Python.

How to write JSON data to a file with Python?

To write JSON data to a file with Python, we can use the open function and the json.dump method.

For instance, we write:

import json

data = {'foo': 1, 'bar': 2}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

to define the data dictionary which we want to write into the JSON file.

Then we call open with 'data.json' to open the data.json file.

'w' lets us open the file with write permission.

encoding sets the text encoding of the file.

Then we call json.dump with data and f to write data to file f.

ensure_ascii set to False to skip ASCII check in the file.

indent is set to 2 to indent each level with 2 spaces.

Conclusion

To write JSON data to a file with Python, we can use the open function and the json.dump method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *