You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中用for循环统计JSON响应中allocations总数量

统计JSON中所有allocations的总数量

当然可以用for循环实现统计,以下是具体步骤和代码:

核心思路

你之前用Object.keys(jsondata[0]).length只能拿到单个对象的属性个数,和allocations数组的元素数量无关。正确的做法是遍历外层数组的每个交易对象,累加每个对象里allocations数组的长度。

for循环实现代码

假设你已经把JSON字符串解析成了JavaScript数组(比如用JSON.parse()):

// 解析后的JSON数据
const data = [
  {"branchCode": "111", "referenceNumber": "2222", "comments": "Write Off", "transactionDate": "2022-02-23T00:00:00", "amount": 0, "accountCode": "MMMM", "accountName": "Metal MMMM", "allocations": [{"branchCode": "111", "referenceNumber": "3333", "allocationDate": "2022-02-23T09:23:57", "ledgerTypeDescription": "Client", "accountCode": "MMMM", "accountName": "Metal MMMM", "amount": -0.02}]},
  {"branchCode": "222", "referenceNumber": "33333", "comments": "To write off historic med fee $0", "transactionDate": "2022-03-24T00:00:00", "amount": 0, "accountCode": "OOOO", "accountName": "Oranga OOOO - AEP", "allocations": [{"branchCode": "222", "referenceNumber": "456", "allocationDate": "2022-03-24T10:39:02", "ledgerTypeDescription": "Client", "accountCode": "OOOOP", "accountName": "Oranga 0000 - AEP", "amount": 94.88}]}
];

let total = 0;
// 遍历外层数组的每个元素
for (let i = 0; i < data.length; i++) {
  // 安全检查:确保当前对象有allocations且是数组
  if (data[i].allocations && Array.isArray(data[i].allocations)) {
    total += data[i].allocations.length;
  }
}

console.log(total); // 输出:2

补充说明

  • 加if判断是为了避免某些对象没有allocations属性或者属性不是数组时报错;
  • 如果你用的是其他语言(比如Python),逻辑完全一致:遍历外层列表,累加每个字典里allocations列表的长度。

内容的提问来源于stack exchange,提问作者sandhya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:44:59