如何从JSON文件中打印特定键的值?现有代码输出全部内容
问题描述
我想从下面的JSON文件中提取特定键对应的值,但运行现有Python代码后会输出全部内容:
reda.json 文件内容
[{"alice": 24, "bob": 27}, {"carl": 33}, {"carl": 55}, {"user": "user2"}, {"user": "user2"}, {"user": "123"}]
现有Python代码
import json filename = 'reda.json' json_data = json.load(open('reda.json')) if type(json_data) is dict: json_data = [json_data] for i in json_data: print(i)
解决方案
只需修改循环逻辑,针对目标键做判断和提取即可实现需求:
示例1:提取单个特定键(以carl为例)
import json filename = 'reda.json' # 指定要提取的目标键 target_key = "carl" json_data = json.load(open(filename)) if type(json_data) is dict: json_data = [json_data] for item in json_data: # 检查当前字典是否包含目标键,避免报错 if target_key in item: print(item[target_key])
运行后输出:
33 55
示例2:提取多个特定键(以user和bob为例)
如果需要提取多个键的值,可以遍历目标键列表:
import json filename = 'reda.json' # 指定多个要提取的目标键 target_keys = ["user", "bob"] json_data = json.load(open(filename)) if type(json_data) is dict: json_data = [json_data] for item in json_data: for key in target_keys: if key in item: print(f"{key}: {item[key]}")
运行后输出:
bob: 27 user: user2 user: user2 user: 123
核心说明
- 保留原代码中判断
json_data类型的逻辑,确保统一处理字典或列表格式的JSON数据; - 通过
in关键字检查键是否存在,避免键不存在时抛出KeyError; - 只需修改
target_key或target_keys的值,就能灵活提取不同键对应内容。
内容的提问来源于stack exchange,提问作者Alesia Thiel
相关产品推荐
相关产品推荐

