You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:21:07