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

如何在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

  1. Incorrect max("timestamp") usage: You're trying to get the latest message by timestamp, but max("timestamp") just returns the string "timestamp" itself—you need to compare the actual timestamp values from your messages list.
  2. 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).
  3. 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, use msg['phone_number'] or msg['text'] when iterating over the list.
  • Find the latest entry: Use max(messages, key=lambda msg: msg['timestamp'])—ISO 8601 timestamps (like your 2021-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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:27:28