Eswar
Eswar

Reputation: 9

Convert dataframe into JSON file

Dataframe:

Name    Location code   ID  Dept    Details Fbk
Kirsh   HD12    76  Admin   "Age:25; Location : ""SF""; From: ""London""; Marital stays: ""Single"";"   Good
John    HD12    87  Support "Age:35; Location : ""SF""; From: ""Chicago""; Marital stays: ""Single"";"  Good 

Desired output:

{
“Kirsh”: {
    “Location code”:”HD12”,
    “ID”: “76”,
    “Dept”: “IT”,
     “Details”: {
         “Age”:”25”;,
         “Location”:”SF”;,
         “From”: "London";,
         “Marital stays”: "Single";,
         }
      “Fbk”: “good”
   },
“John”: {
    “Location code”:”HD12”,
    “ID”: “87”,
    “Dept”: “Support”,
     “Details”: {
         “Age”:”35”;,
         “Location”:”SF”;,
         “From”: "chicago";,
         “Marital stays”: "Single";,
         }
      “Fbk”: “good”
    }
}

Upvotes: 0

Views: 82

Answers (1)

TriveniReddy
TriveniReddy

Reputation: 11

import pandas as pd
import json

df = pd.DataFrame({'name':['a','b','c','d'],'age':[10,20,30,40],'address':['e','f','g','h']})

df_without_name = data1.loc[:, df.columns!='name']

dict_wihtout_name = df_without_name.to_dict(orient='records')

dict_index_by_name = dict(zip(df['name'], df_without_name))

print(json.dumps(dict_index_by_name, indent=2))

Output:

{
  "a": {
    "age": 10,
    "address": "e"
  },
  "b": {
    "age": 20,
    "address": "f"
  },
  "c": {
    "age": 30,
    "address": "g"
  },
  "d": {
    "age": 40,
    "address": "h"
  }
}

Answering the comment posted by @Eswar:

If a field has multiple values then you can store it as a tuple in the dataframe. Check this answer - https://stackoverflow.com/a/74584666/1788146 on how to store tuple values in pandas dataframe.

Upvotes: 1

Related Questions