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

如何在Python中获取JSON结构里特定键(如agentName)的值?

Extracting agentName from Nested JSON in Python

Got it, let's break down exactly how to grab that agentName value from your provided JSON structure in Python—it's straightforward once you navigate the nested keys properly. Here's what you need to do:

1. Parse the JSON (if it’s a string)

If your data starts as a raw JSON string (not a Python dictionary), first convert it using Python’s built-in json module. This turns the string into a mutable dictionary you can work with.

Example code:

import json

# Your JSON structure as a string
json_str = '''{
    "metaData": {
        "fields": [ "id", "path", "time", "userid", "type", "size", "lastProcessed", "numProcessed" ],
        "queueStatus": {
            "agentId": "publish-xxxxx",
            "agentName": "publish-xxxxx",
            "isBlocked": false,
            "isPaused": false,
            "lastProcessTime": -1,
            "nextRetryPeriod": -1524578525793,
            "processingSince": -1,
            "time": 1524578525792
        },
        "root": "queue"
    },
    "queue": []
}'''

# Convert to a Python dictionary
data = json.loads(json_str)

2. Access the nested agentName key

Once you have the dictionary, you can chain bracket notation to navigate down the nested levels:

agent_name = data["metaData"]["queueStatus"]["agentName"]
print(agent_name)  # Output: publish-xxxxx

If there’s a chance any nested key might be missing (to avoid a frustrating KeyError), use the get() method with default values:

# Return None if any key is missing
agent_name = data.get("metaData", {}).get("queueStatus", {}).get("agentName")

# Or set a custom default value like "Unknown Agent"
agent_name = data.get("metaData", {}).get("queueStatus", {}).get("agentName", "Unknown Agent")

Alternatively, use a try-except block to catch errors explicitly:

try:
    agent_name = data["metaData"]["queueStatus"]["agentName"]
except KeyError as e:
    print(f"Oops, missing key: {e}")
    agent_name = "Unknown Agent"

That’s all there is to it! The core idea is just stepping through the nested structure, and adding safeguards if your data might have inconsistencies.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:26:28