Creating a JSON in RMarkdown and then reading/parsing it in JavaScript

Viewed 32

I have an RMarkdown like this:

```r
library(jsonlite)
library(odbc)
library(dplyr)


arrest_data <- tbl(criminal_history_db, sql("select * from 
arrests_table)
"
))

arrest_data <- as.data.frame(arrest_data) 

arrest_data_JSON <- toJSON(arrest_data,dataframe="columns")

write(arrest_data_JSON, "//my_files/arrest_data.JSON")

```


```{js}
  //this fails
  $.getJSON("//my_files/arrest_data.JSON", function(json) {
      console.log(json); // this will show the info in console
  });
```

All of this works and I'm able to produce a JSON. But when I try to read in the local JSON using JavaScript, it of course fails due to a CORS error:

Is there a way to have JavaScript read in the JSON I've created using R syntax? In other words, eliminate the step where I'm saving the JSON locally? I don't have a server framework, I'd like everything to be self-contained in RMarkdown.

Maybe this would work if the JSON was hosted online somewhere, like Box or Sharepoint?

1 Answers

I don't know whether this helps, but if you run a server in the current directory before knitting then it works. That is:

servr::httd()
# knit your file
servr::daemon_stop(1)

Tested with:

```{r}
library(jsonlite)
write(toJSON(list(1, 2, 3)), "test.json")
```

```{js}
$.getJSON("test.json", function(json) {
  console.log(json); // this will show the info in console
});
```
Related