从MongoDB使用Pandas将字典转换为行

2024-09-29 17:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个来自MongoDB的测试,我需要转换成MySQL。但是有时有不止一个“代理”,如果是这样的话,我需要每个代理在它们自己的行上,并且该代理应该具有相同的“display_name”。例如,沃尔特应该让格洛丽亚坐在一排,巴布坐在下一排,而沃尔特·莫斯利则坐在“姓名”下

  [{'name': 'Loomis, Gloria',
  'primaryemail': 'gloria@gmail.com',
  'primaryphone': '212-382-1121'},
 {'name': 'Hogson, Barb',
  'primaryemail': 'bho124@aol.com',
  'primaryphone': ''}]

enter image description here

我已经试过了,但它只是分割出了键/值

a,b,c = [[d[e] for d in test] for e in sorted(test[0].keys())]
print(a,b,c)

这是原始的JSON格式:

{'_id': ObjectId('58e6ececafb08d6'),
  'item_type': 'Contributor',
  'role': 0,
  'short_bio': 'Walter Mosley (b. 1952)',
  'firebrand_id': 1588,
  'display_name': 'Walter Mosley',
  'first_name': 'Walter',
  'last_name': 'Mosley',
  'slug': 'walter-mosley',
  'updated': datetime.datetime(2020, 1, 7, 8, 17, 11, 926000),
  'image': 'https://s3.amazonaws.com/8588-book-contributor.jpg',
  'social_media_name': '',
  'social_media_link': '',
  'website': '',
  'agents': [{'name': 'Loomis, Gloria',
    'primaryemail': 'gloria@gmail.com',
    'primaryphone': '212-382-1121'},
   {'name': 'Hogson, Barb',
    'primaryemail': 'bho124@aol.com',
    'primaryphone': ''}],
  'estates': [],
  'deleted': False}

Tags: namecom代理displaygmailwaltergloriabarb
1条回答
网友
1楼 · 发布于 2024-09-29 17:17:42

如果您的JSON文件中有一组字典,请尝试以下操作:

JSON输入:

inputJSON = [{'item_type': 'Contributor',
            'role': 0,
            'short_bio': 'Walter Mosley (b. 1952)',
            'firebrand_id': 1588,
            'display_name': 'Walter Mosley',
            'first_name': 'Walter',
            'last_name': 'Mosley',
            'slug': 'walter-mosley',
            'image': 'https://s3.amazonaws.com/8588-book-contributor.jpg',
            'social_media_name': '',
            'social_media_link': '',
            'website': '',
            'agents': [{'name': 'Loomis, Gloria',
                        'primaryemail': 'gloria@gmail.com',
                        'primaryphone': '212-382-1121'},
                       {'name': 'Hogson, Barb',
                        'primaryemail': 'bho124@aol.com',
                        'primaryphone': ''}],
            'estates': [],
            'deleted': False}]

代码:

import copy 

finalJSON = []

for each in inputJSON:
    for agnt in each.get('agents'):
        newObj = copy.deepcopy(each)
        newObj['agents'] = agnt
        finalJSON.append(newObj)

print(finalJSON)

相关问题 更多 >

    热门问题