开发者社区> 问答> 正文

从JSON提取特定密钥

我正在使用请求库,Python 3.6和SMS平台的Swagger API。我对如何从此JSON层次结构中提取特定的key:value感到有些困惑。

这是API文档的URL:api docs

我正在尝试根据ID向端点查询特定的电话号码。

这是要查询的URL:https://api.kenect.com/v1/conversations/ \ * \ * ID \ * \ *这是JSON层次结构,因此我想使用“ phoneNumbers”键和“数字的值:

    {
  "archiveDate": 1514801105185,
  "assignedTeamId": 0,
  "assignedTeamName": "string",
  "assignedUser": {
    "departmentId": 1234,
    "firstName": "John",
    "id": 1234,
    "inactiveDate": 1514801105185,
    "includeSignature": true,
    "lastName": "Doe",
    "messageSignature": "Best, John Doe",
    "username": "jdoe@mymail.com"
  },
  "contact": {
    "createdDate": 1514801105185,
    "emailAddress": "contact@email.com",
    "externalId": "8adf-7865",
    "firstActiveDate": 1514801105185,
    "firstName": "Jane",
    "groups": [
      {
        "createdDate": 1514801105185,
        "id": 1234,
        "locationId": 1234,
        "name": "the inner circle",
        "updatedDate": 1514801105185
      }
    ],
    "id": 1234,
    "inactiveDate": 1514801105185,
    "lastContacted": 1514801105185,
    "lastName": "Doe",
    "locationId": 12345,
    "note": "string",
    "phoneNumbers": [
      {
        "city": "Pleasant Grove",
        "country": "US",
        "createdDate": 1514801105185,
        "id": 1234,
        "messageOptInDate": 1514801105185,
        "messageStopDate": 1514801105185,
        "number": "+18015552671",
        "primary": true,
        "sentOptInMessageDate": 1514801105185,
        "smsCapable": true,
        "state": "UT",
        "status": true,
        "type": "CELL",
        "updatedDate": 1514801105185,
        "zipCode": 84062
      }
    ],
    "reviewRequestSent": 1514801105185,
    "source": "LIGHTSPEED",
    "updatedDate": 1514801105185
  },
  "createdDate": 1514801105185,
  "dataAssigned": 0,
  "id": 1234,
  "lastMessageType": "FACEBOOK",
  "lastSent": 1514801105185,
  "locationId": 0,
  "messages": [
    {
      "assignedUserId": 0,
      "attachments": [
        {
          "contentType": "string",
          "createdDate": 1514801105185,
          "friendlyName": "string",
          "id": 1234,
          "md5": "string",
          "size": 16384,
          "thumbnailBase64": "string",
          "updatedDate": 1514801105185
        }
      ],
      "body": "string",
      "contactId": 0,
      "conversationId": 0,
      "error": "string",
      "id": 1234,
      "kind": "string",
      "locationId": 0,
      "outgoing": true,
      "readDate": 0,
      "respondedDate": 0,
      "reviewRequest": true,
      "sentDate": 0,
      "status": "string",
      "type": "FACEBOOK"
    }
  ],
  "newConversation": true,
  "read": true,
  "responded": true,
  "snippet": "string",
  "subject": "string",
  "updatedDate": 1514801105185
}

最后,这是我正在尝试的代码。我曾使用类似的功能从同一端点获取消息正文,但不适用于电话号码。

url='https://api.kenect.com/v1/conversations/'
h = {'accept': recContentType,
    'content-type': recContentType,
    'x-api-token': apiToken,
    'x-api-Key': apiKey}
p={'id': id}

response=requests.get(url + id, headers=h, params=p).json()

for item in response['phoneNumber']:
    pnum = item['number']
    print(pnum)

我在这里做错了什么?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 15:03:41 598 0
1 条回答
写回答
取消 提交回答
  • 这是您获取号码所需的路径:

    .contact.phoneNumbers[0].number
    

    因此,您将需要以下内容:

    number = response['contact']['phoneNumbers'][0]['number']
    print(number)
    

    或编辑您的代码:

    url='https://api.kenect.com/v1/conversations/'
    h = {'accept': recContentType,
        'content-type': recContentType,
        'x-api-token': apiToken,
        'x-api-Key': apiKey}
    p={'id': id}
    
    response=requests.get(url + id, headers=h, params=p).json()
    
    for item in response['contact']['phoneNumbers']:
        pnum = item['number']
        print(pnum)
    

    根据以下注释,如果json中的字段丢失,则上面的代码可能会导致错误。例如,如果“响应”没有“联系”,那么就会出现问题。

    请考虑在上面的代码中添加一些防弹措施,如下所示:

    url='https://api.kenect.com/v1/conversations/'
    h = {'accept': recContentType,
        'content-type': recContentType,
        'x-api-token': apiToken,
        'x-api-Key': apiKey}
    p={'id': id}
    
    response=requests.get(url + id, headers=h, params=p).json()
    
    if response:
      if 'contact' in response:
        if 'phoneNumbers' in response['contact']:
          for item in response['contact']['phoneNumbers']:
            pnum = item['number']
            print(pnum)
    

    我认为在新版本的代码中有足够的检查方法来避免您在下面的注释中描述的错误。现在,我们仅在响应不为空且包含“联系人”键(而该键又必须包含“ phoneNumbers”键)时处理响应。当phoneNumber不包含数字,但是不会产生错误时,仍有机会打印None。请注意,pnum可能为None。

    回答来源:stackoverflow

    2020-03-24 15:21:39
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载