Python无法从Power BI API返回的JSON中提取id值求助
解决Power BI API返回JSON中提取id的问题
你的返回JSON结构里,value字段是一个数组(列表),里面包含符合过滤条件的工作空间对象。要提取id,需要先访问数组中的元素,再获取对应字段。
具体提取代码
在你解析完JSON之后,添加以下代码即可:
# 提取第一个匹配的工作空间id if groups.get("value"): # 先判断value列表是否非空 workspace_id = groups["value"][0]["id"] print(f"工作空间ID: {workspace_id}") else: print("未找到匹配的工作空间")
完整代码示例(整合后)
import json, requests, pandas as pd try: from azure.identity import ClientSecretCredential except Exception: from azure.identity import ClientSecretCredential tenant = 'xxxxxxxxxx' client = 'yyyyyyyyyyy' client_secret = 'zzzzzzzzzzzzzz' api = 'https://analysis.windows.net/powerbi/api/.default' # 生成服务主体的访问令牌 auth = ClientSecretCredential(authority = 'https://login.microsoftonline.com/', tenant_id = tenant, client_id = client, client_secret = client_secret) access_token = auth.get_token(api) access_token = access_token.token print('\n认证成功。') base_url = 'https://api.powerbi.com/v1.0/myorg/' header = {'Authorization': f'Bearer {access_token}'} base_url_expand = f'{base_url}groups?$filter=name%20eq%20%27TestName%27' # 发送HTTP GET请求 groups_response = requests.get(base_url_expand, headers=header) # 打印响应状态码 print(groups_response) try: groups = json.loads(groups_response.content) # 格式化打印JSON print(json.dumps(groups, indent=4, sort_keys=True)) # 提取id if groups.get("value"): workspace_id = groups["value"][0]["id"] print(f"\n提取到的工作空间ID: {workspace_id}") else: print("\n未找到名为TestName的工作空间") except Exception as e: print('\n请求失败:', e)
补充说明
- 你的
$filter条件匹配到了1个结果(@odata.count: 1),所以value列表只有1个元素,用[0]直接访问即可。 - 如果存在多个匹配结果,可以遍历
value列表来获取所有id:
for workspace in groups["value"]: print(f"工作空间名称: {workspace['name']}, ID: {workspace['id']}")
内容的提问来源于stack exchange,提问作者Joy
相关产品推荐
相关产品推荐

