Search code examples
rv8

Parse JSON in R using V8 $eval?


If we open chrome developer console (command + option + j), go the javascript console, and enter

JSON.parse('{ "name":"John"}');

which returns {name: "John"}

but when we run the same javascript in R using V8 (using the example here), it returns a different result

library(V8)
ctx <- v8()
ctx$eval("JSON.parse('{\"name\":\"John\"}');")

# "[object Object]"

How can we get V8::eval() to return the correct result?

Note

  • The documentation may hold some clues (I've tried a few things from there but nothing successfully)

Solution

  • "[object Object]" is the result of calling toString on a JSON object in JavaScript. ctx$eval returns the correct JavaScript object but, before passing it over to R, its toString JavaScript method is invoked.

    But you will nevertheless be able to use the object as expected — you just need to assign it to a variable, e.g.

    ctx$eval("let result = JSON.parse('{\"name\":\"John\"}');")
    

    If you want to get the JSON into R, then going via V8 is a huge detour, because the communication between R and V8 is already JSON-encoded. Use jsonlite::fromJSON instead.

    Nevertheless, I guess you could do

    ctx$get("result")
    

    … which internally calls JSON.stringify in JavaScript, followed by jsonlite::fromJSON in R … so you are going back and forth between object and JSON string several times.