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

如何在Python中读取多层大括号嵌套的JSON数据?

读取多层嵌套JSON获取最内层name字段的解决方案

问题根源

你写的JSON索引语法完全不对——不能把嵌套结构直接塞进方括号,必须一层一层按键名访问。

正确的逐层访问写法

假设你的launcher_profiles.json结构是这种多层嵌套:

{
  "profiles": {
    "053abfb0fb7451c291b9149ea7df88c8": {
      "name": "我的MC游戏存档"
    }
  }
}

对应的正确代码应该是这样:

import json 
import argparse

# 先处理命令行参数(如果用了argparse的话)
parser = argparse.ArgumentParser()
parser.add_argument('--mc_path', required=True)
args = parser.parse_args()

# 只读模式打开文件就行,不用r+
with open(args.mc_path + "launcher_profiles.json", "r") as profiles:
    data = json.load(profiles)

# 逐层取:先拿profiles字典,再拿指定的profile ID,最后取name
target_profile_id = "053abfb0fb7451c291b9149ea7df88c8"
profile_name = data["profiles"][target_profile_id]["name"]
print(profile_name)

如果有多个profile,批量获取name

要是JSON里有多个游戏存档,不想硬编码ID,可以遍历所有profile:

# 遍历profiles下的所有键值对,打印每个存档的ID和name
for profile_id, details in data["profiles"].items():
    print(f"存档ID: {profile_id}, 存档名称: {details['name']}")

避免KeyError的小技巧

如果不确定某个键是否存在(比如可能有缺失的profile),用get()方法安全获取:

# 不存在时返回None,不会报错
profile_name = data.get("profiles", {}).get(target_profile_id, {}).get("name")

内容的提问来源于stack exchange,提问作者Pogman69

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:54:37