1

I have the following code for R Plumber API server

library(jsonlite)
library(data.table)

#' Home endpoint
#' @get /
function(){
  df <- data.table(msg = "Welcome")
  toJSON(df)
}

It gives me ["[{\"msg\":\"Welcome\"}]"] result on API.

How to replace \" on " symbol to make it more human-friendly when working in a browser or Postman? Expected result is "msg":"Welcome".

Thanks!

Andrii
  • 2,843
  • 27
  • 33
  • Yes, but in browsers and Postman I see these \"msg\":\"Welcome\" format. How to make it more human-friendly like "msg":"Welcome". Thanks – Andrii Mar 29 '20 at 17:58
  • 1
    Isn't the `toJSON` done internally? What if you just `return(df)` instead of manually converting it? – r2evans Mar 29 '20 at 22:42
  • Said differently, `cat(as.character(jsonlite::toJSON(jsonlite::toJSON(data.table(msg = "Welcome")))), "\n")` produces that output on my console, suggesting that your single call to `toJSON` is one of two calls to it. – r2evans Mar 29 '20 at 22:44
  • 1
    @HongOoi, I reopened the question since your dupe-question was about manually editing out backslashes, but this question was ultimately about mis-use of `plumber` mechanisms. `sub` and friends would have ultimately failed in the `plumber` environment. – r2evans Mar 30 '20 at 05:53

1 Answers1

1

plumber already jsonifies it, you are doubling it. Try this:

#' Home endpoint
#' @get /
function(){
  df <- data.table::data.table(msg = "Welcome")
  return(df)
}

And then in my console, I ran:

pr <- plumber::plumb("~/StackOverflow/4393334/60918243.R")
pr$run()
# Starting server to listen on port 5225
# Running the swagger UI at http://127.0.0.1:5225/__swagger__/

And then on my bash shell:

$ curl -s localhost:5225
[{"msg":"Welcome"}]
r2evans
  • 141,215
  • 6
  • 77
  • 149