Search code examples
rapihttrqualtricsjsonlite

How do I convert a data table to this JSON object format in R?


I'm attempting to use this Qualtrics API endpoint (https://api.qualtrics.com/0cc0b9dcffc6f-start-a-delete-survey-responses-job) with R to bulk-remove responses from a survey by using httr and jsonlite R packages. It is important to leave the data input as-is because the script should let someone copy/paste in a series of response id’s directly from an Excel doc.

Here is my current code with dummy data (everything except for the post request code):

install.packages(c("httr", "jsonlite"))
library(httr)
library(jsonlite)

data <- read.table(text='
R_010101010101010
R_010101010101010
R_010101010101010
R_010101010101010
R_010101010101010
')
colnames(data) <- 'responseId'

allResponses <- list()
for (row in 1:nrow(data)) {
  response <- list(responseId=data[row, 1],decrementQuotas=TRUE)
  allResponses <- append(allResponses, response)
}

postData <- toJSON(list(deletes=allResponses))
print(postData)

I’m getting an error when trying to submit the POST request because the body of the request is not the right format. It needs to be in this format:

{
  "deletes": [
    {
      "responseId": "R_1234",
      "decrementQuotas": true
    }
  ]
}

But what my code prints is this

{"deletes":{"responseId":["R_010101010101010"],"decrementQuotas":[true],"responseId.1":["R_010101010101010"],"decrementQuotas.1":[true],"responseId.2":["R_010101010101010"],"decrementQuotas.2":[true],"responseId.3":["R_010101010101010"],"decrementQuotas.3":[true],"responseId.4":["R_010101010101010"],"decrementQuotas.4":[true]}} 

Can you all help me coerce this data into the correct JSON format?


Solution

  • Be careful with append. Right now it's not building the list the way you want. You would do the loop more like

    allResponses <- list()
    for (row in 1:nrow(data)) {
      response <- list(responseId=data[row, 1],decrementQuotas=TRUE)
      allResponses <- append(allResponses, list(response))
    }
    
    postData <- toJSON(list(deletes=allResponses), auto_unbox = TRUE)
    cat(postData)
    # {"deletes":[{"responseId":"R_010101010101010","decrementQuotas":true},
    # {"responseId":"R_010101010101010","decrementQuotas":true},
    # {"responseId":"R_010101010101010","decrementQuotas":true},
    # {"responseId":"R_010101010101010","decrementQuotas":true},
    # {"responseId":"R_010101010101010","decrementQuotas":true}]}
    

    Here we also use auto_unbox to remove the extra brackets

    But rather than usign the loop, a better way to make the list would be to use something like lapply in the first place

    allResponses <- lapply(1:nrow(data), function(row) {
      list(responseId=data[row, 1],decrementQuotas=TRUE)
    })
    

    No need for the loop and append in this case.