Python中如何处理CoinMarketCap API返回的JSON数据并美化输出?
Great question! The data you're retrieving is a list containing a single dictionary—so first, we can extract that dictionary to simplify working with it. From there, there are a few straightforward ways to format it into a more readable, clean list.
Step 1: Extract the Dictionary from the List
Your current output is wrapped in square brackets [], which means it's a list. Since there's only one entry, we can pull out the dictionary directly:
import urllib.request import json with urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") as url: data = json.loads(url.read().decode()) # Extract the Cardano data dictionary from the list cardano_data = data[0]
Option 1: Use pprint for Automatic Pretty Printing
Python's built-in pprint (pretty print) module will automatically format the dictionary into a structured, easy-to-read layout without extra work:
import pprint # Print the formatted data pprint.pprint(cardano_data)
Example Output:
{'24h_volume_usd': '213316000.0', 'available_supply': '25927070538.0', 'id': 'cardano', 'last_updated': '1515768856', 'market_cap_usd': '21227011191.0', 'max_supply': '45000000000.0', 'name': 'Cardano', 'percent_change_1h': '0.19', 'percent_change_24h': '13.13', 'percent_change_7d': '-19.93', 'price_btc': '0.00005809', 'price_usd': '0.81872', 'rank': '5', 'symbol': 'ADA', 'total_supply': '31112483745.0'}
Option 2: Create a Custom Formatted Bullet List
If you want a more polished, human-friendly list (with formatted currency values), loop through the dictionary's key-value pairs and format each entry:
print("📊 Cardano Market Data:\n") for key, value in cardano_data.items(): # Format values for readability if key in ['price_usd', 'market_cap_usd', '24h_volume_usd']: formatted_value = f"${float(value):,.2f}" elif key == 'price_btc': formatted_value = f"₿{float(value):,.8f}" elif 'supply' in key: formatted_value = f"{float(value):,.0f}" else: formatted_value = value # Make keys more readable (replace underscores and capitalize) readable_key = key.replace('_', ' ').title() print(f"- {readable_key}: {formatted_value}")
Example Output:
📊 Cardano Market Data: - Id: cardano - Name: Cardano - Symbol: ADA - Rank: 5 - Price Usd: $0.82 - Price Btc: ₿0.00005809 - 24h Volume Usd: $213,316,000.00 - Market Cap Usd: $21,227,011,191.00 - Available Supply: 25,927,070,538 - Total Supply: 31,112,483,745 - Max Supply: 45,000,000,000 - Percent Change 1h: 0.19 - Percent Change 24h: 13.13 - Percent Change 7d: -19.93 - Last Updated: 1515768856
This approach lets you tailor the output exactly how you want it—whether that's adding currency symbols, commas for large numbers, or just making the keys easier to read.
内容的提问来源于stack exchange,提问作者Jeff S

