如何在python中对嵌套数组中的嵌套json对象进行计数

时间:2018-05-18 07:25:04

标签: python json

如何在所有动作中获得对象总数?

目前我在下面的这个片段中没有成功咀嚼,但我尝试挖掘节点失败了。

import json

RESULTS = 'sample.json'
with open(RESULTS) as f:
    data = json.load(f)
    results = data
print(len(results[0]['result']['movements'])) #Expected: 3

sample.json

[
  {
    "result": {
      "TempId": "369477387",
      "movements": [
        {
          "date": "2018-05-03",
          "credit": 100.0,
          "shorttext": "My<br/>Expense "
        },
        {
          "date": "2018-05-03",
          "debit": 200.0,
          "shorttext": "My<br/>F\u00dcR"
        }
      ]
    }
  },
  {
    "result": {
      "TempId": "369477395",
      "movements": []
    }
  },
  {
    "result": {
      "TempId": "369477402",
      "movements": [
        {
          "date": "2018-05-07",
          "credit": 100.0,
          "shorttext": "My<br/>Expense "
        }
      ]
    }
  }
]

1 个答案:

答案 0 :(得分:2)

使用列表推导,您可以从示例列表中的每个元素中找出movements的数量。

然后只需在sum列表上应用count方法即可找出总和。

count = sum([len(item['result']['movements']) for item in sample])

输出

>> count
3