Search code examples
rjsonjsonliter-highcharter

Is there a way to remove quotes from the output of a data frame entered into the toJSON function in R?


I am trying to output a data frame in R as a json file to use for highcharts plots that I am making outside R. This is what my output looks like :-

[{"name":"alpha","value":1},{"name":"brave","value":2},{"name":"charlie","value":3}]

However, I want my output to look like this :-

[{name:"alpha",value:1},{name:"brave",value:2} {name:"charlie",value:3}] 

What should I do so that the names of my data frame (in this case name and value) are not put into quotes? If converting my data into a json file is not the best way, what else can/should I do?

library(tidyverse)
library(jsonlite)
data = tibble(name = c("alpha", "bravo", "charlie"), 
              value = c(1, 2, 3))
output = toJSON(data, dataframe="rows")
write(output, "output.txt")

Solution

  • One possible way using regex, removing quotes from values appearing before colon :

    json_string <- jsonlite::toJSON(data, dataframe="rows")
    
    temp <- stringr::str_replace_all(json_string, '"(\\w+)"\\s*:', '\\1:')
    cat(temp)
    #[{name:"alpha",value:1},{name:"bravo",value:2},{name:"charlie",value:3}]
    
    write(temp, "output.txt")