[英]How to count nested json objects from a nested array in python
如何獲得所有運動中的對象總數?
目前,盡管下面所有嘗試挖掘節點的嘗試都失敗了,但我在下面的代碼片段中並未獲得成功。
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 "
}
]
}
}
]
使用列表推導,您可以從樣本列表中找出每個元素的movements
次數。
然后只需將sum
方法應用於count
列表即可找出總和。
count = sum([len(item['result']['movements']) for item in sample])
輸出量
>> count
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.