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.

Advertisements

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

Result

In the execution of this Python code, you can see a data.json file is created.

Here JSON data is formatted. It looks nice. So writing JSON files is easy.

Related posts

Author: Srini

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