简体   繁体   中英

Excel Pandas DataFrame to nested JSON

I have a Pandas Dataframe as follows

Project Issue_Type Summary  Description  customfield_18433 fields
0 ARD    Story      Test     Description  OG048933
1 ARD    Epic       Test 2   Description  OG048933

I need to output it to a json of the following structure:

[
{
    "fields": {
       "project":
       {
          "key": "ARD"
       },
       "summary": "test",
       "description": "description",
       "issuetype": {
          "name": "story"
       },
       "customfield_18433": "OG048933"
   }
},
{
    "fields": {
       "project":
       {
          "key": "ARD"
       },
       "summary": "test 2",
       "description": "description",
       "issuetype": {
          "name": "epic"
       },
       "customfield_18433": "OG048933"
   }
}
]

I've gotten the following code but not sure where to go from here

def create_nested_dicts(df):
    return {'project': dict(zip('key',df['Project'])), 'summary': df['Summary'].unique()[0], 'description' : df['Description'].unique()[0], 'issuetype': dict(zip('name',df['issuetype']))}
df = df.groupby(['fields',]).apply(create_nested_dicts)

You could go with some fancy pandas function, or you could simply change the columns you need into a dict :

df["Project"] = [{"key":i} for i in df["Project"]]
df["Issue_Type"] = [{"name":i} for i in df["Issue_Type"]]

s = df.to_dict(orient="records")

print (s)

[{'Project': {'key': 'ARD'}, 'Issue_Type': {'name': 'Story'}, 'Summary': 'Test', 'Description': 'Description', 'customfield_18433': 'OG048933'},
 {'Project': {'key': 'ARD'}, 'Issue_Type': {'name': 'Epic'}, 'Summary': 'Test 2', 'Description': 'Description', 'customfield_18433': 'OG048933'}]

Just do another list comprehension if you need the field type by [{"field":i} for i in s] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM