用python读取json并统计元素数量
假设我们有一个JSON文件,包含以下内容:
{
"fruits": {
"apple": 5,
"banana": 7,
"orange": 3
},
"vegetables": {
"carrot": 2,
"lettuce": 4,
"tomato": 6
}
}
我们可以使用Python的json模块读取该文件,然后统计元素数量:
import json
# 读取JSON文件
with open('example.json', 'r') as f:
data = json.load(f)
# 统计元素数量
count = 0
for key in data:
count += len(data[key])
print(count)
输出结果为:6,即JSON文件中共有6个元素。
原文地址: https://www.cveoy.top/t/topic/fjiD 著作权归作者所有。请勿转载和采集!