Question about how sendCustomMessage converts data.frames in lists to JSON

37 views
Skip to first unread message

Carl Ganz

unread,
Aug 24, 2016, 11:37:02 AM8/24/16
to Shiny - Web Framework for R
Hello,

I thought that when you use session$sendCustomMessage to pass info from the server to the UI that it converts the object to JSON using jsonlite::toJSON, but that doesn't appear to be the case. Here is an example:


df <- list(mydf=data.frame(v1="Hello",v2="World",
                 stringsAsFactors=FALSE))

library(shiny)

ui <- shinyUI(fluidPage(
  singleton(tags$script(HTML(
    "Shiny.addCustomMessageHandler('test-json',function(object) {
      console.log(JSON.stringify(object));
    })"
    ))),
  actionButton("test","Press me")  
  ))

server <- shinyServer(function(input, output, session) {
 
  observeEvent(input$test,{
    print(jsonlite::toJSON(df))
    session$sendCustomMessage('test-json',df)
  })
  
})

# Run the application
shinyApp(ui = ui, server = server)

When I print jsonlite::toJSON(df) I get this:

{ mydf: [ {v1: "Hello", v2: "World"} ] }

But when I pass the object to the UI and print the JSON to the console I get:

{ mydf: { v1: ["Hello"], v2: ["World"] } }

The placement of the brackets is different, and it is causing me some problems. 

Is there a way to ensure that when a data.frame in a list is passed to the UI that the JSON wraps the data.frame in brackets?

Thanks

Joe Cheng

unread,
Aug 24, 2016, 11:40:40 AM8/24/16
to Carl Ganz, Shiny - Web Framework for R
I believe if you call jsonlite::toJSON and pass the result to sendCustomMessage, it'll be smart enough not to double-JSON-encode.

Or if you're developing an htmlwidget you can use this JS function to do the conversion for you: http://www.htmlwidgets.org/develop_advanced.html#htmlwidgets.dataframetod3
--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/198dac0b-f351-42c9-bc93-e7860324bd17%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages