我想遍历下面的json数组,以提取所有的referencevalvalues和相应的paymentid到一个
{
"payments": [{
"paymentID": "xxx",
"externalReferences": [{
"referenceKind": "TRADE_ID",
"referenceValue": "xxx"
}, {
"referenceKind": "ID",
"referenceValue": "xxx"
}]
}, {
"paymentID": "xxx",
"externalReferences": [{
"referenceKind": "ID",
"referenceValue": "xxx"
}]
}]
}
下面的片段仅在单个付款和单个外部引用的情况下提取。我希望能够做到多支付和多个外部引用以及。
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])
看看您的结构,首先您必须遍历支付中的每个字典,然后遍历它们的外部引用。所以下面的代码应该提取所有的引用值和他们的支付id到一个字典(并追加到一个列表)
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)
这段代码应该在data
字典中输出一个包含所有参考值及其支付id的字典列表(假设您将数据读入data
变量)