Saturday, May 31, 2025

Exceldata to nested json object

 import pandas as pd

import json


def insert_nested_key(obj, key_path, value):

    keys = key_path.split(".")

    for key in keys[:-1]:

        obj = obj.setdefault(key, {})

    obj[keys[-1]] = value


def excel_to_nested_json(input_excel_path, output_json_path="output_data.json"):

    df = pd.read_excel(input_excel_path)

    records = []


    for _, row in df.iterrows():

        json_obj = {}

        for col, val in row.items():

            insert_nested_key(json_obj, col, val)

        records.append(json_obj)


    with open(output_json_path, "w") as f:

        json.dump(records, f, indent=2)


    print(f"✅ Nested JSON with {len(records)} record(s) saved to: {output_json_path}")


if __name__ == "__main__":

    excel_to_nested_json("your_excel_file.xlsx")


No comments:

Post a Comment