如何在Python中从JSON响应提取数据并集成计量平台与短信API实现自动短信通知
Fixing Your SMS Integration & JSON Data Extraction
Let's walk through fixing your code and properly extracting the phone numbers and message text from your JSON response to send SMS via Africa's Talking.
First, Let's Spot the Issues in Your Original Code
- Incorrect
max("timestamp")usage: You're trying to get the latest message by timestamp, butmax("timestamp")just returns the string "timestamp" itself—you need to compare the actual timestamp values from your messages list. - Wrong list indexing: When looping through
json_response['messages'], you're trying to access it like a dictionary (json_response['messages']['text']) but it's a list. You need to use the loop index (or better, iterate directly over the list items). - GET request with payload: Most APIs don't expect a payload in a GET request—double-check if your SparkMeter endpoint should use POST instead, but we'll focus on the data extraction part first.
Solution 1: Send Only the Latest Message (By Timestamp)
If you only want to send the most recent message (based on timestamp), you can use Python's max() function with a lambda to find the newest entry:
import africastalking import requests import json # Initialize Africa's Talking SDK username = "sandbox" api_key = "auth_key" # Replace with your actual sandbox API key africastalking.initialize(username, api_key) sms = africastalking.SMS # Fetch messages from SparkMeter API url = "https://nay-bokani.sparkmeter.cloud/api/v0/sms/outgoing" headers = { 'Content-Type': 'application/json', 'Authentication-Token': 'auth_key' # Replace with your actual token } # Note: GET requests typically don't include payload—remove data if not needed response = requests.get(url, headers=headers) json_response = response.json() if json_response['status'] == 'success': messages = json_response.get('messages', []) if not messages: print("No messages found.") else: # Find the message with the latest timestamp latest_message = max(messages, key=lambda msg: msg['timestamp']) # Send the SMS send_response = sms.send(latest_message['text'], [latest_message['phone_number']]) print(f"Sent latest message to {latest_message['phone_number']}: {send_response}") else: print(f"API request failed: {json_response.get('error', 'Unknown error')}")
Solution 2: Send All Messages
If you want to send every message from the response, just iterate directly over the messages list:
import africastalking import requests import json # Initialize Africa's Talking SDK username = "sandbox" api_key = "auth_key" africastalking.initialize(username, api_key) sms = africastalking.SMS # Fetch messages from SparkMeter API url = "https://nay-bokani.sparkmeter.cloud/api/v0/sms/outgoing" headers = { 'Content-Type': 'application/json', 'Authentication-Token': 'auth_key' } response = requests.get(url, headers=headers) json_response = response.json() if json_response['status'] == 'success': messages = json_response.get('messages', []) if not messages: print("No messages found.") else: # Loop through all messages and send SMS for msg in messages: phone = msg['phone_number'] text = msg['text'] send_response = sms.send(text, [phone]) print(f"Sent to {phone}: {send_response}") else: print(f"API request failed: {json_response.get('error', 'Unknown error')}")
Key Takeaways for JSON Data Extraction
- Access list elements correctly:
json_response['messages']is a list of dictionaries. To get individual fields, usemsg['phone_number']ormsg['text']when iterating over the list. - Find the latest entry: Use
max(messages, key=lambda msg: msg['timestamp'])—ISO 8601 timestamps (like your2021-06-09T10:32:11.885605) can be compared as strings directly. - Handle empty data: Use
json_response.get('messages', [])to safely get the messages list, even if the key is missing (it returns an empty list instead of throwing an error).
内容的提问来源于stack exchange,提问作者remi
相关产品推荐
相关产品推荐

