boltthrower
boltthrower

Reputation: 1250

Convert each row of pandas DataFrame to nested JSON object

I have a dataframe that has several columns like [name, email, country, city, type, time, x_completions] as follows:

I want to convert each row of this dataframe to a JSON object but group some columns into a dict and call it user_info like { "name": "XYZ", "email": "[email protected]", "country": "USA", "city": "NYC"}

Basically, I want to convert each row into a JSON object of the following structure:

{ "type":"Login", "user_id":"002203293023", "user_info":{ "name":"XYZ", "email":"[email protected]", "country":"USA", "city":"NYC" }, "other_info":{ "x_completed":"4" }, "time":1562932893 }

I'm not sure how to go about converting groups of columns to dicts within JSON objects. All the other similar questions on SO deal with some form of groupby operation which I don't think I need here.

Upvotes: 2

Views: 1434

Answers (1)

Alexander
Alexander

Reputation: 109526

Use a list comprehension to iterate through each row in your dataframe.

[{
   "type": "Login",
   "user_id": row['user_id'],
   "user_info":{
      "name": row['name'],
      "email": row['email'],
      "country": row['country'],
      "city": row['city']
   },
   "other_info":{
      "x_completed": row['x_completions']
   },
   "time": row['time']
} for _, row in df.iterrows()]

Upvotes: 4

Related Questions