Modifying plumber JSON response

Hi, I am reading a mongoDB document and fetching some keys of a document and want to return that as output. But it is not coming in a desired format.

My Mongo document:

{
    "_id" : ObjectId("5e8ac613349951694201d663"),
    "StartTime" : ISODate("2020-04-06T06:02:58.537Z"),
    "TrainingProcess" : "completed",
    "EndTime" : "2020-04-06 11:34:40",
    "TrainingStatus" : "completed",
    "Progress" : "100%"
}

My plumber.R request:

#'@get /get_status

function(){
  status <- training_status$find(query = '{"TrainingStatus":"running"}')
  output <- list(status['TrainingStatus'], status['Progress'])
  return(output)
}

My output:

[
    [
        {
            "TrainingStatus": "completed"
        }
    ],
    [
        {
            "Progress": "100%"
        }
    ]
]

I need something like this:

{
"TrainingStatus" : "completed",
 "Progress" : "100%"
}

I also tried output <- jsonlite::toJSON(output, pretty = TRUE, auto_unbox = TRUE) but it didn't work

How to get the output in the desired format?

Your output object has a very nested structure. (Which is what is being returned.).

Using only a single [ will result in a list being returned. To get just the value, use [[.

Be sure to set the serializer with auto_unbox = TRUE to avoid getting an array result for each of the values.

Try this function...

#' @get /get_status
#' @serializer json list(auto_unbox=TRUE)
function() {
  status <- training_status$find(query = '{"TrainingStatus":"running"}')
  output <- list(TrainingStatus = status[['TrainingStatus']], Progress = status[['Progress']])
  return(output)
}

Another way would be to use the list objects status['TrainingStatus'] and status['Progress'] by appending them together...

output <- append(status['TrainingStatus'], status['Progress'])
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Yay! Glad it worked. :smile:

If you don't mind marking the question as solved with my reply, that would be great!

1 Like

Thanks a lot!
I tried the first method and it worked. :smiley: