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

使用Python处理VEX API返回数据:提取有效信息需求

Extracting Valid Data from VEX API Response

Got it, let's break down how to clean up that messy VEX API response and pull out only the info you care about. Your original code fetches the raw data, but we can refine it to filter redundant fields and make the output usable.

Step 1: Improve the Base Code (Add Robustness)

First, let's fix up the original code to handle potential errors (like network issues) and use proper context managers for the URL request:

import json
from pprint import pprint
from urllib.request import urlopen, HTTPError

try:
    with urlopen('https://api.vexdb.io/v1/get_rankings?team=35211C') as response:
        raw_data = response.read().decode('utf-8')  # Decode bytes to string for reliable JSON parsing
        full_data = json.loads(raw_data)
except HTTPError as e:
    print(f"Failed to fetch data: {e}")
except json.JSONDecodeError:
    print("Error parsing JSON response from API")
else:
    pprint(full_data)

This adds safety nets for common issues and ensures we're working with a properly decoded string (your original code might work without decoding, but it's safer to include it for consistency).

Step 2: Extract Only Valid/Useful Fields

The API returns a result list with objects packed with fields—let's narrow it down to only the data you need. You can choose two approaches:

Approach 1: Keep Specific Desired Fields

Define exactly which fields you want to retain (customize this list based on your needs):

# List of fields you want to keep (adjust as needed)
desired_fields = ['team', 'rank', 'division', 'wins', 'losses', 'ties', 'opr', 'ccwm', 'max_score']

# Filter the raw data to only include these fields
cleaned_rankings = [
    {key: entry[key] for key in desired_fields if key in entry}
    for entry in full_data['result']
]

# Print the cleaned, concise output
pprint(cleaned_rankings)

This will give you a list of dictionaries with no extra redundant data—only the fields you specified.

Approach 2: Exclude Redundant Fields

If you'd rather block specific unneeded fields instead of listing desired ones:

# List of fields to exclude (e.g., sku, trsp, ap if they're irrelevant to you)
exclude_fields = ['sku', 'trsp', 'ap', 'sp']

cleaned_rankings = [
    {key: val for key, val in entry.items() if key not in exclude_fields}
    for entry in full_data['result']
]

pprint(cleaned_rankings)

Step 3: Handle Edge Cases

Add a check for empty results (in case the team has no ranking data):

if not full_data['result']:
    print("No ranking data found for this team")
else:
    # Run your cleaning code here
    pprint(cleaned_rankings)

Bonus: Format Output for Readability

If you want a more human-friendly view (like a table), use the tabulate library (install with pip install tabulate):

from tabulate import tabulate

# Convert cleaned data to table format
table_rows = [list(entry.values()) for entry in cleaned_rankings]
table_headers = list(cleaned_rankings[0].keys())

print(tabulate(table_rows, headers=table_headers, tablefmt='grid'))

This will output a neat, easy-to-read grid instead of raw dictionaries.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:36:23