Home > database >  How do I access nested elements inside a json array in python
How do I access nested elements inside a json array in python

Time:12-02

I want to iterate over the below json array to extract all the referenceValues and the corresponding paymentIDs into one

{
    "payments": [{
        "paymentID": "xxx",
        "externalReferences": [{
            "referenceKind": "TRADE_ID",
            "referenceValue": "xxx"
        }, {
            "referenceKind": "ID",
            "referenceValue": "xxx"
        }]
    }, {
        "paymentID": "xxx",
        "externalReferences": [{
            "referenceKind": "ID",
            "referenceValue": "xxx"
        }]
    }]
}

The below piece only extracts in case of a single payment and single externalreferences. I want to be able to do it for multiple payments and multiple externalreferences as well.

payment_ids = []
for notification in notifications:

    payments= [(payment[0], payment["externalReferences"][0]["referenceValue"])
                 for payment in notification[0][0]]

    if payments[0][1] in invoice_ids:
         payment_ids.extend([payment[0] for payment in payments])

CodePudding user response:

Looking at your structure, first you have to iterate through every dictionary in payments, then iterate through their external references. So the below code should extract all reference values and their payment IDs to a dictionary (and append to a list)

refVals = [] # List of all reference values

for payment in data["payments"]:
    for reference in payment["externalReferences"]:
        refVals.append({ # Dictionary of the current values
                "referenceValue": reference["referenceValue"], # The current reference value
                "paymentID": payment["paymentID"] # The current payment ID
            })

print(refVals)

This code should output a list of a dictionary with all reference values and their payment IDs, in the data dictionary (assuming you read your data into the data variable)

  • Related