How to Create JSON file in Python

Here’s a sample Python logic to create a JSON file. As you know, JSON data is of key and value. Across applications, JSON files are popular to exchange data. Interestingly, Python also supports JSON files.

Logic to create json file

Here, the data is an object where we place 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.


Creating JSON file: Python logic

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

Python logic to create json file

Output from the python script: The result

After executing the Python script, you can find the data.json file is generated and the JSON data you can see is formatted. It looks nice. So writing JSON files is easy.

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.