【问题标题】:Parse multiple level of JSON in Python在 Python 中解析多级 JSON
【发布时间】:2021-12-28 23:39:17
【问题描述】:

我正在尝试解析 item 并将其放在同一级别的 products 中,如果 item 具有多个值,我将获得多个具有相同 item_id 的产品等。

    data = event['products']['item']
    item = []
    while number < len(data)
        item.append(data[number])
        number = number+1

【问题讨论】:

    标签: python arrays json python-3.x


    【解决方案1】:

    您需要在每次循环中复制event['products'],并将data[number] 合并到其中。

    products = event['products']
    result = []
    for item in products['item']:
        new_prod = products.copy()
        del new_prod['item']
        new_prod.update(item)
        result.append(new_prod)
    

    【讨论】:

    • 但是产品和项目都在数组中。我认为这会对更新有问题
    • 它正在创建一个新数组,它所在的数组不相关。
    【解决方案2】:

    其中一种方法;

    data = {
            "products": [
                {
                    "created_time": "1234567890",
                    "updated_time": "1234567890",
                    "item": [
                        {
                            "Status": "active",
                            "quantity": 59,
                            "Images": []
                        },
                        {
                            "Status": "passive",
                            "quantity": 60,
                            "Images": []
                        }
                    ],
                    "item_id": 123,
                    "primary_category": 345,
                    "marketImages": [],
                    "attributes": {
                        "name": "Sample"
                    }
                }
            ]
    }
    output = {}
    output['products'] = []
    for product in data['products']:
        for item in product['item']:
            product1 = product.copy()
            del product1['item']
            product1.update(item)
            output['products'].append(product1)
    print (output)
    

    输出:

    {'products': [{'created_time': '1234567890', 'updated_time': '1234567890', 'item_id': 123, 'primary_category': 345, 'marketImages': [], 'attributes': {'name': 'Sample'}, 'Status': 'active', 'quantity': 59, 'Images': []}, {'created_time': '1234567890', 'updated_time': '1234567890', 'item_id': 123, 'primary_category': 345, 'marketImages': [], 'attributes': {'name': 'Sample'}, 'Status': 'passive', 'quantity': 60, 'Images': []}]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2013-02-02
      • 1970-01-01
      相关资源
      最近更新 更多