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

Python中如何根据指定变量匹配JSON键并返回对应值?

Fix: Get Specific JSON Key's Value Matching a Variable in Python

Hey there, let's sort out why your code is spitting out all JSON values instead of just the one tied to your q variable.

The Issue With Your Current Code

Right now, your search function loops through every key in the loaded JSON data and prints every corresponding value—there's no check to see if the key matches the q parameter. That's why you're getting the full list of values instead of just the role_id value you're targeting.

The Fix

Since JSON objects in Python act like dictionaries, you don't need a loop here. You can directly access the value using the key stored in q, plus a quick check to avoid errors if someone passes a key that doesn't exist in the JSON.

Here's the revised code:

import json

def search(q):
    with open("config.json") as f:
        data = json.load(f)
    # Check if the requested key exists in the JSON data
    if q in data:
        print(data[q])
    else:
        print(f"Key '{q}' wasn't found in config.json")

search(q="role_id")

How This Works

  • We still load the JSON file into a Python dictionary (data) like before.
  • Instead of looping through all keys, we first verify if q is a valid key in the dictionary.
  • If it exists, we print the exact value you want—when q is "role_id", this will output the role ID string from your JSON.
  • The else clause adds a safety net to handle invalid key requests, so your code won't crash with a KeyError.

Expected Output

When you run this with q="role_id", you'll get:

REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:27:40