【问题标题】:Mapping JSON key-value pairs from source to destination using Python使用 Python 将 JSON 键值对从源映射到目标
【发布时间】:2021-04-30 06:34:58
【问题描述】:

使用 Python requests 我想从一个来源抓取一段 JSON 并将其发布到目的地。然而,接收到的 JSON 的结构与目标所需的结构有所不同,所以我的问题是,如何最好地将项目从源结构映射到目标结构?

为了说明,假设我们得到了约翰和玛丽购买的所有商品的清单。现在我们想发布购买的单个物品,将它们链接到购买它们的个人(注意:实际用例涉及数千个条目,因此我正在寻找一种可以相应扩展的方法):

源 JSON:

{
    'Total Results': 2, 
    'Results': [
        {
            'Name': 'John',
            'Age': 25,
            'Purchases': [
                {
                    'Fruits': {
                        'Type': 'Apple',
                        'Quantity': 3,
                        'Color': 'Red'}
                        }, 
                {
                'Veggie': {
                    'Type': 'Salad', 
                    'Quantity': 2, 
                    'Color': 'Green'
                    }
                }
            ]
        },
        {
            'Name': 'Mary',
            'Age': 20, 
            'Purchases': [
                {
                    'Fruits': {
                        'Type': 'Orange',
                        'Quantity': 2,
                        'Color': 'Orange'
                    }
                }
            ]
        }
    ]
}

目标 JSON:


{
    [
        {
            'Purchase': 'Apple', 
            'Purchased by': 'John',
            'Quantity': 3, 
            'Type': 'Red',
        }, 
        {
            'Purchase': 'Salad', 
            'Purchased by': 'John', 
            'Quantity': 2, 
            'Type': 'Green',
        },
        {
            'Purchase': 'Orange', 
            'Purchased by': 'Mary',
            'Quantity': 2, 
            'Type': 'Orange',
        }
    ]
}

对此的任何帮助将不胜感激!干杯!

【问题讨论】:

  • 能否也添加您当前的实现代码?

标签: python json python-requests


【解决方案1】:

只需考虑遍历字典。

res = []

for result in d['Results']:
    value = {}
    for purchase in result['Purchases']:
        item = list(purchase.values())[0]
        value['Purchase'] = item['Type']
        value['Purchased by'] = result['Name']
        value['Quantity'] = item['Quantity']
        value['Type'] = item['Color']
        res.append(value)
pprint(res)

[{'Purchase': 'Apple', 'Purchased by': 'John', 'Quantity': 3, 'Type': 'Red'},
 {'Purchase': 'Salad', 'Purchased by': 'John', 'Quantity': 2, 'Type': 'Green'},
 {'Purchase': 'Orange', 'Purchased by': 'Mary', 'Quantity': 2, 'Type': 'Orange'}]

【讨论】:

  • 谢谢,所以基本上你的建议是遍历每个结果的字典,然后在其中抓取购买的物品,同时为这些值分配新的键,并将所有这些放在然后将新字典放入新列表中,对吗?对于最里面的循环,我不完全理解item = list(purchase.values())[0]您能否详细说明(包括索引)?谢谢
  • @Zaphod dict.values() 获取字典 dict 的所有值。 index0 表示获取第一个值。
猜你喜欢
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
相关资源
最近更新 更多