如何用Python从API返回的JSON中提取角色与权限名称?
No worries, this is a super common task—let’s break it down step by step. First, we’ll turn that raw JSON string into a Python-friendly data structure (dictionaries and lists), then traverse that structure to pull out exactly the values you need.
Step 1: Parse the JSON Response
First up, use Python’s built-in json module to convert the raw JSON output into something you can manipulate. If you’re using the requests library to fetch the API data, you can even skip a step by using the .json() method directly on the response object.
Step 2: Understand Your JSON Structure
The exact code depends on how your JSON is structured, so let’s use a typical role-permission setup as an example. Suppose your formatted JSON looks like this:
{ "roles": [ { "role_name": "Administrator", "permissions": [ {"permission_name": "Manage Users"}, {"permission_name": "Edit System Settings"} ] }, { "role_name": "Content Editor", "permissions": [ {"permission_name": "Create Articles"}, {"permission_name": "Edit Own Content"} ] } ] }
Step 3: Full Working Example Code
Here’s how you’d fetch, parse, and extract the roles and permissions in one go:
import requests import json # Replace this with your actual API endpoint api_url = "https://your-api-source.com/roles-permissions" response = requests.get(api_url) response.raise_for_status() # Catch any request errors # Parse JSON into a Python dictionary role_data = response.json() # Loop through roles and extract the values you want for role in role_data["roles"]: print(f"Role: *{role['role_name']}*") print("Assigned Permissions:") for permission in role["permissions"]: print(f"- {permission['permission_name']}") print("---")
Tweaks for Your Specific JSON
If your JSON has a different layout (like permissions being a simple list of strings, or roles nested under a data key), just adjust the keys you reference. For example:
- If permissions are plain strings:
for permission in role["permissions"]: print(f"- {permission}") - If roles are nested under
data:for role in role_data["data"]["roles"]:
You can always print the parsed role_data variable to inspect the exact structure and adjust your code accordingly.
内容的提问来源于stack exchange,提问作者GaryK26

