1

I have a following excel file with two sheets: Sheet 1

and

Sheet 2

I want to convert this excel into a json format using python that looks like this:

 {
   "app_id_c":"string",
   "cust_id_n":"string",
   "laa_app_a":"string",
   "laa_promc":"string",
   "laa_branch":"string",
   "laa_app_type_o":"string",
   "los_input_from_sas":[
      "lsi_app_id_":'string',
      "lsi_cust_type_c":'string'
      ]
  }

I tried using in built JSON excel to json library but it is giving me series of json instead of nested and I can't utilise another sheet to be part of same JSON

WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53

1 Answers1

0

First of all, you have to provide a minimal sample easy to copy and paste not an image of samples. But I have created a minimal sample similar to your images. It doesn't change the solution.

Read xlsx files and convert them to list of dictionaries in Python, then you will have objects like these:

sheet1 = [{
    "app_id_c": "116092749",
    "cust_id_n": "95014843",
    "laa_app_a": "36",
    "laa_promc": "504627",
    "laa_branch": "8",
    "laa_app_type_o": "C",
}]

sheet2 = [
    {
        "lsi_app_id_": "116092749",
        "lsi_cust_type_c": "G",
    },
    {
        "lsi_app_id_": "116092749",
        "lsi_cust_type_c": "G",
    },
]

After having the above mentioned objects in Python, you can create the desired json structure by the following script:

for i in sheet1:
    i["los_input_from_sas"] = list()
    for j in sheet2:
        if i["app_id_c"] == j["lsi_app_id_"]:
            i["los_input_from_sas"].append(j)

sheet1 = json.dumps(sheet1)

print(sheet1)

And this is the printed output:

[
  {
    "app_id_c": "116092749",
    "cust_id_n": "95014843",
    "laa_app_a": "36",
    "laa_promc": "504627",
    "laa_branch": "8",
    "laa_app_type_o": "C",
    "los_input_from_sas": [
      {
        "lsi_app_id_": "116092749",
        "lsi_cust_type_c": "G"
      },
      {
        "lsi_app_id_": "116092749",
        "lsi_cust_type_c": "G"
      }
    ]
  }
]

UPDATE: Here are some solution to read xlsx files and convert to python dict.

Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25