Reputation: 349
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")
Upvotes: 1
Views: 577
Reputation: 519
An alternative way -
library(tidyverse)
library(jsonlite)
data = tibble(name = c("alpha", "bravo", "charlie"), value = c(1, 2, 3))
output = toJSON(data)
output=gsub("\"(\\w*)\":", "\\1:", output,perl=TRUE)
print(output)
Output -
[{name:"alpha",value:1},{name:"bravo",value:2},{name:"charlie",value:3}]
Upvotes: 0
Reputation:
Not sure how to do this inside toJSON but you can use mgsub
from the qdap
library
sapply(names(data), function(name_i){
output <<- mgsub(paste0("\"", name_i, "\""), name_i, output)})
That gives you
output
[{name:"alpha",value:1},{name:"bravo",value:2},{name:"charlie",value:3}]
Upvotes: 1
Reputation: 389145
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")
Upvotes: 1