从ID JSON响应surveymonkey API v3获取价值

时间:2017-06-26 11:53:36

标签: json python-3.x surveymonkey

我对此非常陌生,非常感谢任何指导或帮助。

我目前有一个调查回复列表,我接到以下电话:

import requests
import json

client = requests.session()

headers = {
    "Authorization": "bearer %s" % "AccessTOKEN",
    "Content-Type": "application/json"
}

HOST = "https://api.surveymonkey.net"
SURVEY_LIST_ENDPOINT = "/v3/surveys/SURVEYID/responses/bulk"

uri = "%s%s" % (HOST, SURVEY_LIST_ENDPOINT)

response = client.get(uri, headers=headers)

response_json = response.json()

print(response_json['data'])

我从以下内容得到回复:

{
  "per_page": 50,
  "total": 5114,
  "data": [
    {
      "total_time": 40,
      "href": "https://api.surveymonkey.net/v3/surveys/surveyID/responses/ID",
      "custom_variables": {},
      "ip_address": "IP ADDRESS",
      "id": "ID",
      "logic_path": {},
      "date_modified": "2015-12-01T05:31:22+00:00",
      "response_status": "completed",
      "custom_value": "",
      "analyze_url": "http://www.surveymonkey.com/analyze/browse/ID?respondent_id=ID",
      "pages": [
        {
          "id": "220527570",
          "questions": [
            {
              "id": "872991507",
              "answers": [
                {
                  "choice_id": "9573882449",
                  "row_id": "9573882439"
                }
              ]

我想获得实际的响应值,例如"是,否,可能"来自choice_id?

很多人提前感谢, PON

1 个答案:

答案 0 :(得分:1)

现在还没有从API返回的直接有效负载也有答案文本。

您需要先获取survey details

SURVEY_DETAIL_ENDPOINT = "/v3/surveys/SURVEYID/details"
uri = "%s%s" % (HOST, SURVEY_DETAIL_ENDPOINT)

response = client.get(uri, headers=headers)

survey_data = response.json()

然后您可能想要循环搜索答案以创建查找字典。大致类似于:

answer_dict = {}
for page in survey_data['pages']:
    for question in page['questions']:

        # Rows, choices, other, and cols all make up the possible answers
        answers = question['answers'].get('rows', [])\
            + question['answers'].get('choices', [])\
            + question['answers'].get('other', [])\
            + question['answers'].get('cols', [])

        for answer in answers:
            answer_dict[answer['id']] = answer

我知道这对于for循环看起来很粗糙,但你基本上只是遍历整个调查。这是有效的,因为选择ID是全局唯一的(即列,行,选项等之间没有冲突。)。

然后,您可以通过answer_dict[answer['choice_id']]对响应中的任何answer轻松获取整个答案详细信息。

如果API本身允许选项用响应为您填写答案文本,那不是一个坏主意。