Skip to content

Instantly share code, notes, and snippets.

@johnjosephhorton
Created November 12, 2010 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnjosephhorton/674300 to your computer and use it in GitHub Desktop.
Save johnjosephhorton/674300 to your computer and use it in GitHub Desktop.
R function for turning a data frame into JSON suitable for use in Protovis
entity.write <- function(x){
out = as.character(x)
out = paste("\"", x, "\"", sep="")
out
}
toJSONdf <- function(x){
str = "["
for(row in 1:(dim(x)[1])){
first_entry = TRUE
i = 0
for (n in names(x)){
i = i + 1
if (first_entry) {
str = paste(str, "{", sep="")
first_entry = FALSE
}
str = paste(str,deparse(n),":", entity.write(x[row, n]),sep="")
if(i < dim(x)[2]){
str = paste(str, ",", sep="")
}
}
str = paste(str, "}", sep="")
if (row < dim(x)[1]){
str = paste(str, ",", sep="")
}
}
str = paste(str, "]", sep="")
str
}
@johnjosephhorton
Copy link
Author

The rjson package is great, but it turns data frames into [x:{1,2,3}, y:{1,2,3}] where for Protovis, you want [{x:1, y:1}, {x:2,y:2}, {x:3,y:3}]. Hoping there is a smarter way to do this (and that someone else wants to add all the error checking and message).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment