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

Python中如何访问JSON数据里profileChanges内的profile字段?

Python处理JSON:访问嵌套的profile字段

问题描述

我是编程新手,正在尝试用Python编写程序读取JSON文件,并将其中指定数据(而非全部)保存到另一个文件。我搜索了解析数据的方法,但仍有疑问。

以下是JSON文件的片段:

{
 "profileRevision": 548789,
 "profileId": "campaign",
 "profileChangesBaseRevision": 548789,
 "profileChanges": [
  {
   "changeType": "fullProfileUpdate",
   "profile": {
    "_id": "2da4f079f8984cc48e84fc99dace495d",
    "created": "2018-03-29T11:02:15.190Z",
    "updated": "2022-10-31T17:34:43.284Z",
    "rvn": 548789,
    "wipeNumber": 9,
    "accountId": "63881e614ef543b2932c70fed1196f34",
    "profileId": "campaign",
    "version": "refund_teddy_perks_september_2022",
    "items": {
     "8ec8f13f-6bf6-4933-a7db-43767a055e66": {
      "templateId": "Quest:heroquest_loadout_constructor_2",
      "attributes": {
       "quest_state": "Claimed",
       "creation_time": "min",
       "last_state_change_time": "2019-05-18T16:09:12.750Z",
       "completion_complete_pve03_diff26_loadout_constructor": 300,
       "level": -1,
       "item_seen": true,
       "sent_new_notification": true,
       "quest_rarity": "uncommon",
       "xp_reward_scalar": 1
      },
      "quantity": 1
     },
     "6940c71b-c74b-4581-9f1e-c0a87e246884": {
      "templateId": "Worker:workerbasic_sr_t01",
      "attributes": {
       "gender": "2",
       "personality": "Homebase.Worker.Personality.IsDreamer",
       "level": 1,
       "item_seen": true,
       "squad_slot_idx": -1,
       "portrait": "WorkerPortrait:IconDef-WorkerPortrait-Dreamer-F02",
       "building_slot_used": -1,
       "set_bonus": "Homebase.Worker.SetBonus.IsMeleeDamageLow"
     }
    }
   }
  }
 ]
}

我已能访问profileChanges,编写了如下代码将其保存到新文件file2:

myjsonfile= open("file.json",'r') 
jsondata=myjsonfile.read() 
obj=json.loads(jsondata)  
ciso=obj['profileChanges']
for i in ciso:
    print(i)
with open("file2", "w") as outfile:
    json.dump( ciso, outfile, indent=1)

但问题是,我无法以同样的方式通过解析新文件访问profileChanges内部的profile字段,不知道该怎么做。

解决方法

核心原因

你保存到file2的profileChanges是一个列表(数组),里面的每个元素才是包含profile字段的字典。所以读取file2后,需要先遍历这个列表,再从中取出profile。

1. 读取file2并访问profile字段的代码

import json

# 读取file2文件
with open("file2", "r") as infile:
    profile_changes = json.load(infile)

# 遍历列表,逐个获取每个元素里的profile
for change in profile_changes:
    # 用get()方法更安全,避免键不存在时报错
    profile = change.get("profile")
    if profile:
        print(profile)
        # 若要访问profile内部的具体字段,比如items
        items = profile.get("items")
        if items:
            print("Profile内的物品数据:", items)

2. 优化建议:直接提取profile保存(跳过中间步骤)

如果最终只需要profile数据,没必要先保存profileChanges到file2,可以直接从原JSON中提取profile并保存,后续读取会更简单:

import json

# 读取原JSON文件
with open("file.json", "r") as myjsonfile:
    obj = json.load(myjsonfile)

# 提取所有有效profile(过滤掉没有profile的元素)
profiles = [change.get("profile") for change in obj["profileChanges"] if change.get("profile")]

# 保存profile到新文件
with open("profiles.json", "w") as outfile:
    json.dump(profiles, outfile, indent=1)

# 读取profiles.json的简化代码
with open("profiles.json", "r") as infile:
    saved_profiles = json.load(infile)
for p in saved_profiles:
    print("Profile ID:", p["_id"])  # 直接访问profile内部字段

关键知识点

  • JSON中的[]对应Python的列表,需通过遍历或索引(如profile_changes[0])访问元素
  • JSON中的{}对应Python的字典,可通过键名(如change["profile"])或get()方法取值(get()能避免键不存在时抛出异常)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:50:48