遍历一个JSON文件可以使用递归或者迭代的方法来实现。下面分别给出两种方法的代码示例:
import json
def traverse_json(data):
if isinstance(data, dict):
for key, value in data.items():
print(f"Key: {key}")
traverse_json(value)
elif isinstance(data, list):
for item in data:
traverse_json(item)
else:
print(f"Value: {data}")
# 读取JSON文件
with open('data.json') as file:
json_data = json.load(file)
# 遍历JSON数据
traverse_json(json_data)
import json
# 读取JSON文件
with open('data.json') as file:
json_data = json.load(file)
# 使用栈来迭代遍历JSON数据
stack = [(json_data, "")]
while stack:
data, prefix = stack.pop()
if isinstance(data, dict):
for key, value in data.items():
new_prefix = f"{prefix}.{key}" if prefix else key
stack.append((value, new_prefix))
elif isinstance(data, list):
for i, item in enumerate(data):
new_prefix = f"{prefix}[{i}]" if prefix else f"[{i}]"
stack.append((item, new_prefix))
else:
print(f"{prefix}: {data}")
以上两种方法都可以遍历一个JSON文件,并且输出每个键值对或者值。你可以根据你的需求进行修改和适配。