-1

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])

1 Answers1

2

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)

  • 2
    It gives the reference values, but not the paymentIDs. maybe a dict `paymentID => [refValues]` is more what is requested here? – Cpt.Hook Dec 01 '22 at 13:27
  • 2
    @Cpt.Hook valid point, I'll modify it now – quantumintern Dec 01 '22 at 13:29
  • 1
    Assuming that the paymendIDs are unique (bold assumtion, I know), we don't need a list of dicts but could just use the paymentIDs as keys in the dict... – Cpt.Hook Dec 01 '22 at 13:33
  • 2
    and as a matter of style: It's hard to remeber what `a` and `i` are. Why not calling them `payment` and `reference`? like `for reference in payment['externalReferences']` is almost english. ;) – Cpt.Hook Dec 01 '22 at 13:36
  • 2
    Thanks for the tip, modified it! I agree, easier to read – quantumintern Dec 01 '22 at 13:38
  • Still for the output I'd use: `{'payment_xyz': ['ref1', 'ref2', ...], 'payment_abc': ['ref45'], ... }`, but in general everything is here and the problem should be solvable with this. – Cpt.Hook Dec 01 '22 at 13:41