Python中如何根据指定变量匹配JSON键并返回对应值?
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
qis a valid key in the dictionary. - If it exists, we print the exact value you want—when
qis "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

