假设我们有一个 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 个元素。

Python 读取 JSON 文件并统计元素数量

原文地址: https://www.cveoy.top/t/topic/oaOM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录