Home > Back-end >  Parse multiple level of JSON in Python
Parse multiple level of JSON in Python

Time:11-18

I'm trying to parse item and put it in same level of products and if item has multiple values I would get multiple product with same item_id and etc.

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

CodePudding user response:

you need to make a copy of event['products'] each time through the loop, and merge data[number] into it.

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)

CodePudding user response:

One of the approaches;

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)

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': []}]}
  • Related