0

I'm trying to use R to create some API requests and using the jsonlite package to do so. I have an element in my JSON request named selected that needs to be set to "::total::": "". Everything I have tried results in the addition of a "\". I usually get something like this ... "::total::\": \"". Any ideas on how to solve this problem?

Here is my code:

          reportsuite.id = "myRSID" 
      date.from = 2017-06-23
      date.to = 2017-08-23
      metrics = c("pageviews", "visits", "uniquevisitors")
      elements = myVar
      top = 0
      start = 0
      selected = '::total::": "'
      search = c()
      search.type = "or"
      date.granularity = "day"
      segment.id = ""
      segment.inline = ""
      classification = character(0)
      anomaly.detection = FALSE
      data.current = TRUE
      expedite = FALSE
      interval.seconds = 5 
      max.attempts = 120
      validate = TRUE
      enqueueOnly = FALSE


        report.description <- c()
        report.description$reportDescription <- c(data.frame(matrix(ncol = 0, 
                                                                    nrow = 1)))
        report.description$reportDescription$dateFrom <- unbox(date.from)
        report.description$reportDescription$dateTo <- unbox(date.to)
        report.description$reportDescription$reportSuiteID <- unbox(reportsuite.id)
        report.description$reportDescription$dateGranularity <- unbox(date.granularity)
        report.description$reportDescription$elementDataEncoding <- unbox("utf8")
        if (segment.inline != "") {
          report.description$reportDescription$segments <- list(segment.inline)
        }
        if (as.list(segment.id)[1] == "") {
          report.description$reportDescription$segment_id <- unbox(segment.id)
        } else {
          report.description$reportDescription$segments <- data.frame(id = segment.id)
        }
        if (anomaly.detection == TRUE) {
          report.description$reportDescription$anomalyDetection <- unbox(anomaly.detection)
        }
        if (data.current == TRUE) {
          report.description$reportDescription$currentData <- unbox(data.current)
        }
        if (expedite == TRUE) {
          report.description$reportDescription$expedite <- unbox(expedite)
        }
        report.description$reportDescription$metrics = data.frame(id = metrics)
        elements.formatted <- list()
        i <- 0
        for (element in elements) {
          i <- i + 1
          if (i == 1) {
            working.element <- list(id = unbox(element), top = unbox(top[1]), 
                                    startingWith = unbox(start))
            if (length(selected) != 0) {
              working.element[["selected"]] <- selected
            }
            if (length(search) != 0) {
              working.element[["search"]] <- list(type = unbox(search.type), 
                                                  keywords = search)
            } 
          } else {
            if (length(top) >= i) {
              working.element <- list(id = unbox(element), 
                                      top = unbox(top[i]))
            } else {
              working.element <- list(id = unbox(element), 
                                      top = unbox("50000"))
            }
          }
          if (length(classification) >= i) {
            working.element[["classification"]] <- unbox(classification[i])
          }
          if (length(elements.formatted) > 0) {
            elements.formatted <- append(elements.formatted, 
                                         list(working.element))
          } else {
            elements.formatted <- list(working.element)
          }
        }
        report.description$reportDescription$elements <- elements.formatted

Results in:

toJSON(report.description)

{"reportDescription":{"dateFrom":"2017-06-23","dateTo":"2017-08-23","reportSuiteID":"myRSID","dateGranularity":"day","elementDataEncoding":"utf8","segment_id":"","currentData":true,"metrics":[{"id":"pageviews"},{"id":"visits"},{"id":"uniquevisitors"}],"elements":[{"id":"evar32","top":0,"startingWith":0,"selected":["::total::\": \""]}]}}

Thanks! Jess

  • 1
    What string are you starting with? A reproducible example would help here. – Rich Scriven Aug 24 '17 at 21:08
  • So I need it to literally look like this: "::total::": "" selected = '::total::": "' results in "::total::\": \"" – Jessica Langford Aug 24 '17 at 21:11
  • So are you saying you don't want the backward slashes? They are required for escaping the double quotes. – acylam Aug 24 '17 at 21:14
  • And how are you setting it? Are you using `gsub`? Something else? And are you sure that the true values *aren't* what you want? Have you compared `cat` and `print` for seeing what you really have? Please make a [reproducible example](https://stackoverflow.com/q/5963269/903061) so that we can see what's going on. And you say *"everything I tried results in the addition of a ."*, but the example you give doesn't seem to include a `.`. – Gregor Thomas Aug 24 '17 at 21:15
  • Okay, this is better, but now could you make it a a *minimal* reproducible example? Is `selected = '::total::": "'; jsonlite::toJSON(selected)` enough to show your problem? – Gregor Thomas Aug 24 '17 at 21:18
  • I've added my code now! Sorry, I should have done that right away. – Jessica Langford Aug 24 '17 at 21:23
  • Also, is what you're trying to produce valid JSON? [How to escape double quotes in JSON?](https://stackoverflow.com/q/15637429) make it look like the backslashes might be appropriate. – Gregor Thomas Aug 24 '17 at 21:23
  • 1
    For what it's worth, you are already getting the right thing. You can see that if you try `nchar("::total::\": \"")`. This returns 13, which is what you'd get if you count `\"` as one character (you can verify this manually). That means that the `\` characters are only printing, but not actually evaluating. If they were evaluating, you would get 15. – Yannis Vassiliadis Aug 24 '17 at 21:23
  • I'm leaning toward Yanni's suggestion. If he's right, possibly a dupe of R-FAQ [Remove backslash from character string](https://stackoverflow.com/q/28204507/903061). – Gregor Thomas Aug 24 '17 at 21:25
  • I think JSON is evaluating the backslashes ... right? Since it appears in the resulting request? – Jessica Langford Aug 24 '17 at 21:28
  • I've tried this request using another API tool with and without the backslashes. The one with backslashes doesn't work, but the one without them does. – Jessica Langford Aug 24 '17 at 21:30
  • @JessicaLangford, if you're going to pass it as an argument to something, maybe you should try `cat("::total::", "\": \"", sep="")`. This outputs `::total::": "`. – Yannis Vassiliadis Aug 24 '17 at 21:39
  • @YannisVassiliadis Any ideas on how to store the value of the cat() function? – Jessica Langford Aug 24 '17 at 21:49
  • @JessicaLangford sorry no idea – Yannis Vassiliadis Aug 24 '17 at 22:13
  • @JessicaLangford The `cat` function is showing you what's really there - you are already storing it. The `print` function does some extra processing, adds escape characters. That is what is explained [in this answer that I linked above](https://stackoverflow.com/a/28204611/903061). – Gregor Thomas Aug 29 '17 at 18:03

0 Answers0