2

I'm having some trouble formatting data my R data frame or table to the JSON file I want.

This is the format I would like to have.

{ "PercentileFromR":
  [ "499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
  [ "0", "7", "38", "124", "271", "388", "442"],
  [ "4", "6", "35", "68", "81", "71", "33"]
]
}

My code is

col1 <- c("499 to 516","517 to 534","535 to 552","553 to 569","570 to 586","587 to 604","605 to 622")
col2 <- c("0","7","38","124","271","388","442")
col3 <- c("4","6","35","68","81","71","33")
tableData <- rbind(col1, col2, col3)

install.packages('jsonlite', dependencies=TRUE, repos='http://cran.rstudio.com/')
library(jsonlite)
exportJSON <- toJSON(tableData, pretty = TRUE)
write(exportJSON, "output.json")

But this is what I get

[
  ["499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
  ["0", "7", "38", "124", "271", "388", "442"],
  ["4", "6", "35", "68", "81", "71", "33"]
]

I was able to get this, but it still isn't the format I'd like:

{"binCategories":"499 to 516","plot1binCount":"0","plot2binCount":"4","NA":"517 to 534","NA":"7","NA":"6","NA":"535 to 552","NA":"38","NA":"35","NA":"553 to 569","NA":"124","NA":"68","NA":"570 to 586","NA":"271","NA":"81","NA":"587 to 604","NA":"388","NA":"71","NA":"605 to 622","NA":"442","NA":"33"}
adrienne
  • 103
  • 1
  • 9

2 Answers2

2

Convert the dataframe into a named list before converting to JSON:

library(jsonlite)
tableData <- rbind(col1, col2, col3)

#make a list and then name the elements.
tableData<-list(tableData)
names(tableData)<-"PercentileFromR"

exportJSON <- toJSON(tableData, pretty = TRUE)
exportJSON

# {
#    "PercentileFromR": [
#       ["499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
#       ["0", "7", "38", "124", "271", "388", "442"],
#       ["4", "6", "35", "68", "81", "71", "33"]
#       ]
# } 
Dave2e
  • 22,192
  • 18
  • 42
  • 50
0

You may manipulate the exportJSON object using gsub with some regexpressions:

exportJSON <- gsub("\\[\n", "\\{ \"PercentileFromR\":\n", exportJSON)
exportJSON <- gsub("\n\\]", "\n\\]\n\\}", exportJSON)
exportJSON

Output is:

{ "PercentileFromR":
  ["499 to 516", "517 to 534", "535 to 552", "553 to 569", "570 to 586", "587 to 604", "605 to 622"],
  ["0", "7", "38", "124", "271", "388", "442"],
  ["4", "6", "35", "68", "81", "71", "33"]
]
} 
symbolrush
  • 7,123
  • 1
  • 39
  • 67