the following function create a json object from excel file , the problem is some of the…
- User
the following function create a json object from excel file , the problem is some of the columns in the sheet have int and string values so the json serialize the int as int and the string as string , i want it to instead of that checks if the values of the columns are mixed between int and string to make the whole column string in a way that the 0 becomes "0" in the json import pandas as pd import json import os
def excel_to_json(excel_file_path): """Convert a given Excel file into a Dictionary where each one of the sheets in the object is represented by a key,value pair.
Args: excel_file_path (str): path to a single excel file. Returns: Dict: A dictionary containing the JSON data. """ json_data = {} xls = pd.ExcelFile(excel_file_path) for sheet_name in xls.sheet_names: df = pd.read_excel(excel_file_path, sheet_name=sheet_name) sheet_json = df.to_dict(orient="list") json_data[sheet_name] = sheet_json return json_datadef process_excel_files(directory): """Convert all the Excel files in a directory to JSON.
Args: directory (str): path to the directory containing the Excel files. """ output_directory = "database/data_temp/json_files" if not os.path.exists(output_directory): os.makedirs(output_directory) for filename in os.listdir(directory): if filename.endswith(".xlsx") or filename.endswith(".xls"): excel_file_path = os.path.join(directory, filename) json_file_path = os.path.join( output_directory, f"{os.path.splitext(filename)[0]}.json" ) json_output = excel_to_json(excel_file_path) with open(json_file_path, "w") as json_file: json.dump(json_output, json_file, indent=4) print(f"Converted '{filename}' to JSON: '{json_file_path}'")directory = "database/data_temp/excel_files" process_excel_files(directory)
- Assistant