微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 Json_response 中提取数据以在 python 中使用

如何解决如何从 Json_response 中提取数据以在 python 中使用

我正在尝试集成两个 API

  1. 来自应通过短信发送通知的计量平台。
  2. API 是一个发送消息的短信平台。

Python 代码

import africastalking
import requests
import json

# Initialize SDK
username = "sandBox" # use 'sandBox' for development in the test environment
# use your sandBox app API key for development in the test environment
api_key = "auth_key"
africastalking.initialize(username,api_key)


# Initialize a service e.g. SMS
sms = africastalking.SMS

url = "https://nay-bokani.sparkmeter.cloud/api/v0/sms/outgoing"

payload = json.dumps({
  "mark_delivered": False
})
headers = {
  'Content-Type': 'application/json','Authentication-Token': 'auth_key'
}

response = requests.request("GET",url,headers=headers,data=payload)

# print()
json_response = response.json()

if json_response['status'] == 'success':
  if json_response["messages"][0]["timestamp"] == max("timestamp"):
    for s in range(len(json_response['messages'])):
      response = sms.send(json_response['messages']['text'],[json_response['messages']['phone_number']])
    print(response)

print(response.text)

json 响应

{
  "error": null,"messages": [ 
    {
      "id": "46186176-ba91-4072-a93e-0fc089dea750","phone_number": "+2348000000000","text": "You've just been credited with N10.00 worth of energy","timestamp": "2021-06-09T10:14:10.795818"
    },{
      "id": "6709099c-22c8-4df5-88e1-24284d8ff61f","phone_number": "+2348111111111","text": "You've just been credited with N500.00 worth of energy","timestamp": "2021-06-09T10:32:11.885605"
    }
  ],"status": "success"
}

我需要能够提取电话号码和文本,并使用它通过短信 API 发送自动短信。我尝试使用最近时间戳进行解析,但是当返回多个json数据时会出现问题。

解决方法

import json

#cannot use the real sms.send function so define a dummy one
def dummy_sms_send(txt,phone):
    print(txt,phone)

json_response = """
{
  "error": null,"messages": [ 
    {
      "id": "46186176-ba91-4072-a93e-0fc089dea750","phone_number": "+2348000000000","text": "You've just been credited with N10.00 worth of energy","timestamp": "2021-06-09T10:14:10.795818"
    },{
      "id": "6709099c-22c8-4df5-88e1-24284d8ff61f","phone_number": "+2348111111111","text": "You've just been credited with N500.00 worth of energy","timestamp": "2021-06-09T10:32:11.885605"
    }
  ],"status": "success"
}
"""

decoded_response = json.loads(json_response)
if decoded_response["status"] == "success":
    for msg in decoded_response["messages"]:
        dummy_sms_send(msg["text"],msg["phone_number"])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。