This tutorial help to create JSON file using python 3. I will get data from the rest API and write data into a JSON file. We will save it into the folder location.
JSON (JavaScript Object Notation) is a popular data format used for representing structured data. This is a common data format for transmitting and receiving data between a server and web application in JSON format.
You can also checkout other python File tutorials:
- How To Read Write Yaml File in Python3
- Read and Write CSV Data Using Python
- How To Read & Update Excel File Using Python
- How To Load Json file Using Python
- Python List Example And Methods
- Convert Python Dictionary To JSON
The sample employee json object :
{ "status": "success", "data": { "id": "2", "employee_name": "Garrett Winters", "employee_salary": "170750", "employee_age": "63", "profile_image": "" } }
Import json module
To work with JSON in Python, we need to import the python JSON module.
import json
How To Write JSON File in Python
We will write JSON file in Python using json.dump()
method. Let’s create json_example.py
file and write the below code into this file.
import sys import requests from colorama import Fore, init, Back, Style import json url = "https://dummy.restapiexample.com" headers = {'Content-Type': 'application/json'} def employees(): try: res_data = [] resp = requests.get(url = url, headers = headers) if resp.status_code == 200: service_data = resp.json() for service in service_data["data"]: if service["employee_name"] != None : tmp = {} tmp['id']=service["id"] tmp['employee_name']=service["employee_name"] res_data.append(tmp) return res_data else : return res_data except Exception as e: print (Fore.RED + "ERROR ! To get employee data.") print(e) return res_data init(convert=True) print("\n") try: emps = employees() print("===========================================================") if len(emps) >= 0: with open('employee.json', 'w') as outfile: json.dump(emps, outfile) print(emps) except Exception as e: print(e) print (Fore.RED + "Error : The emp api") print(Fore.GREEN + "###################### Successfully! created json file. ##############################")
In the above code, Created employees()
method to get data from the rest API using the request package. This method returns the array of employee data.
We have opened a file named employee.txt
in writing mode using 'w'
. If the file doesn’t already exist, it will be created. Then, json.dump()
transforms emps to a JSON string which will be saved in the employee.txt
file.
When you run the program, the employee.txt
file will be created. The file has all employees data.