【问题标题】:How do I access nested elements inside a json array in pythonHow do I access nested elements inside a json array in python
【发布时间】:2022-12-01 21:24:56
【问题描述】:

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

【问题讨论】:

    标签: python arrays json-arrayagg


    【解决方案1】:

    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 append to a list)

    refVals = [] # List of all reference values
    
    for i in data["payments"]:
        for a in i["externalReferences"]:
            refVals.append(a["referenceValue"])
    
    print(refVals)
    

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

    【讨论】:

    • It gives the reference values, but not the paymentIDs. maybe a dict paymentID => [refValues] is more what is requested here?
    • @Cpt.Hook valid point, I'll modify it now
    猜你喜欢
    • 2022-12-01
    • 2022-12-01
    • 2022-01-04
    • 2022-12-01
    • 2022-12-27
    • 2022-12-27
    • 2022-12-01
    • 2022-08-17
    • 2022-12-01
    相关资源
    最近更新 更多