Normalizing json list as values

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-11 18:22:39

问题


I have a problem to normalize a json, I can't find a solution in all the documentation I found.

my json:

{'id': 790005,
 'company_id': 700025,
 'owner_id': {'id': 11300075,
  'name': '*** Alves',
  'email': '*****.alves@***rs.com.br',
  'has_pic': 0,
  'pic_hash': None,
  'active_flag': True,
  'value': 100075},
 'org_id': None,
 'name': 'V****or - 37****376 - Jo****ctor',
 'first_name': 'Vi****r',
 'last_name': '37****76 - - Jo****or',
 'open_deals_count': 0,
 'related_open_deals_count': 0,
 'closed_deals_count': 0,
 'related_closed_deals_count': 0,
 'participant_open_deals_count': 0,
 'participant_closed_deals_count': 0,
 'email_messages_count': 0,
 'activities_count': 0,
 'done_activities_count': 0,
 'undone_activities_count': 0,
 'reference_activities_count': 0,
 'files_count': 0,
 'notes_count': 0,
 'followers_count': 1,
 'won_deals_count': 0,
 'related_won_deals_count': 0,
 'lost_deals_count': 0,
 'related_lost_deals_count': 0,
 'active_flag': True,
 'phone': [{'value': '', 'primary': True}],
 'email': [{'label': '',
   'value': 'vi****es@****k.com',
   'primary': True}],
 'first_char': 'v',
 'update_time': '2020-01-29 17:51:41',
 'add_time': '2019-12-13 20:45:44',
 'visible_to': '1',
 'picture_id': None,
 'next_activity_date': None,
 'next_activity_time': None}

I am not able to unite the values ​​of the key 'phone' and 'email as they are another list of dictionaries.

can you help me?


回答1:


Try:

from pandas.io.json import json_normalize
df = json_normalize(data)
df['email'] = df['email'].apply(pd.Series) # to convert [{}]  --> {} 
df = pd.concat([df, df['email'].apply(pd.Series).add_prefix("email_")], axis=1)
df['phone'] = df['phone'].apply(pd.Series) # to convert [{}]  --> {} 
df = pd.concat([df, df['phone'].apply(pd.Series).add_prefix("phone_")], axis=1)
df.drop(['email', 'phone'], inplace=True, axis=1)

Then access by email_label, email_value ....




回答2:


Not the best answer possible, but very understandable code imho

result = {}
for key,value in x.items():
    if type(x[key]) is not list:
        result[key] = x[key]
     elif type(x[key]) is list:
         for i in x[key]:
            if type(x[key]) is dict:
                 result[key] = x[key]['value']
# Simply using the input and iterating through to get all the relevant information 
# into a new result dictionary

# now we read the info into a df

df = pd.DataFrame.from_dict(result,orient='index')

# You can play around with how you would like to keep the columns, Transpose if you like.


来源:https://stackoverflow.com/questions/60342490/normalizing-json-list-as-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!