In this example program, we will see how to create a JSON file using Python. Let us split that into three different tasks.

  1. Create a JSON object
  2. Create a file in write mode.
  3. Write the JSON into newly create file.

Example – Python Create JSON File

In the below example, we are creating a python object in the variable json_obj. After the data is ready, we are opening a file in write mode using the with command. Now, we use the inbuilt module json and use the function dump() to write the JSON object into the file. Here we are passing two arguments to the function dump(). The first argument is the data, in this case it is the JSON object. Second argument is the file pointer where the data needs to be written.

import json
#Create a JSON Object
json_obj = {}
json_obj['employees'] = []
json_obj['employees'].append({
    'emp_name' : 'John Watson',
    'date_of_join' : '01-01-2015'
    })
#Write the object to file.
with open('example.json','w') as jsonFile:
    json.dump(json_obj, jsonFile)

Run the above code and it will create a JSON file with name “example.json” in the project folder.

Python Create JSON File
Tagged on: