How to Create JSON file in Python

Here’s a sample Python logic to create a JSON file. JSON data is of key and value. JSON files are popular to exchange data between applications. Interestingly, Python supports JSON and you’ll see here how create a JSON file.

How to to create json file

Here is the logic. In data object you can find the JSON information.

data = {
  'value1': 1,
 'value2': 2,
'a_dict_of_values' : {
'd1': 'hello',
'd2': 'world'
'value3': 1.234
with open('data.json', 'w', encoding='utf-8') as f:
  json.dump(data, f, ensure_ascii=False, indent=4)

As I said before, JSON structure has keys and values. Also, a dictionary of data you can add as part of key/value.

Don’t worry. It’s a simple way of writing JSON files. The data.json is a JSON file that we are about to create.

The ‘w’ is the write mode. Encoding is the format that we write to file.

The ‘with open’ is the Python keyword to open a new .json file in write mode. The entire with open, we keep in alias called ‘f’.

The json.dump function is the function that writes data to JSON files. It has four arguments. Those are ‘data’, ‘f’, ensure_ascii’ and indent=4.

The indent parameter writes output in a readable format.


Python logic

You need to import JSON. And, the below is the python logic.

Python logic to create json file

The result of python script

After you run the script, an output file of data.json will create and it has all the formatted JSON data.

Output from the python script

Reference books

Related posts

Good motivational video

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.