Fetching Localytics API Data in R and working with the JSON result

Recently, I’ve been building a dashboard for Find&Save using R, RStudio and Shiny Dashboards and one of our core mobile metrics is 30 day active users for both iOS and Android which I can get from Localytics (our analytics platform) via their API. Googling around I found I’m not reinventing the wheel (via SO) though I did run into a problem where the response failed to convert properly thus the post.

Here’s the original function from SO with some slight tweaks for my needs:

response <- POST(url = localyticsApiUrl, 
                  body=list(
                    app_id=appid,
                    metrics="users",
                    conditions=list(
                      day=c("between", format(Sys.Date() - 31, "%Y-%m-%d"), format(Sys.Date() - 1, "%Y-%m-%d"))
                    )
                  ),
                  encode="json",
                  authenticate(localyticsApiKey,localyticsApiSecret),
                  accept("application/json"),
                  content_type("application/json")
)
stop_for_status(response)

The resulting JSON response wasn’t parsing properly using the code from SO:

content(response, as="text")


Error in mat[, seq_len(n), drop = FALSE] : incorrect number of dimensions
In addition: Warning messages:
1: In mapply(FUN = f, …, SIMPLIFY = FALSE) :
longer argument not a multiple of length of shorter
2: In mapply(FUN = f, …, SIMPLIFY = FALSE) :
longer argument not a multiple of length of shorter

Looking at the request$content the data looked like this (truncated here):

response$content
   [1] 7b 0a 20 20 22 72 65 73 75 6c 74 73 22 3a 20 5b...
   ...

Clearly, this looks like an ASCII version of the JSON response and thus why the SO post  uses the content function for conversion. I took a little different approach to accomplish the same result and avoid the error using rawToChar:

result <- paste(rawToChar(response$content), collapse = "")
  fromJSON(result)

So now to see the results we can use this to view active users for prior 30 days:

> results%contents$users

CC BY-NC-SA 4.0
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.