Get value from ID JSON response surveymonkey API v

2019-04-15 04:45发布

问题:

Im quite new to this, any guidance or help is much appreciated.

I currently have a list of survey response i get form the following call:

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'])

i get a response from as something of the following:

{
  "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"
                }
              ]

I would like to get the actually response value e.g "Yes, No, Maybe" from the choice_id?

many many thanks in advance, Pon

回答1:

There isn't a direct payload returned from the API right now that has the answer text as well.

You'll need to fetch your survey details first:

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

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

survey_data = response.json()

Then you likely want to loop through the answers to create a lookup dictionary. Roughly something like:

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

I know this looks rough with for loops but you're basically just traversing the entire survey. This works because choice IDs are globally unique (i.e. no collisions between columns, rows, choices etc.).

Then you can easily get the entire answer details by doing answer_dict[answer['choice_id']] for any answer in the response.

It wouldn't be a bad idea if the API itself allowed an option to fill in the answer text with the response for you.