#ll <- ToListExplicit(vt_testdata(), unname=FALSE, nameName = "name", childrenName = "children")
vt_make_json <- function(node) {
op <- options("useFancyQuotes")
options(useFancyQuotes=FALSE)
ll <- ToListExplicit(node, unname=FALSE, nameName = "name", childrenName = "children")
json <- paste0("{",dQuote("name"),":",dQuote(ll$name))
childs <- ll$children
levs <- names(childs)
if (length(levs)==0) {
json <- paste0(json,"}")
return(json)
}
json <- paste0(json,",",dQuote("children"),":[{")
for (i in seq_along(levs)) {
lev <- levs[i]
if (i>1) {
json <- paste0(json,"{")
}
json <- paste0(json, dQuote("name"),":",dQuote(childs[[lev]]$name),",")
json <- paste0(json, dQuote("color"),":",dQuote(childs[[lev]]$color),",")
json <- paste0(json, dQuote("children"),":[{")
for (k in seq_along(childs[[lev]]$children)) {
tmp <- childs[[lev]]$children[[k]]
if (k!=1) {
json <- paste0(json,",{")
}
json <- paste0(json, dQuote("name"),":",dQuote(tmp$name),",")
json <- paste0(json, dQuote("weight"),":",tmp$weight,",")
if (!is.null(tmp$color)) {
json <- paste0(json, dQuote("color"),":",dQuote(tmp$color),",")
}
json <- paste0(json, dQuote("code"),":",dQuote(tmp$code),"}")
}
json <- paste0(json,"]}")
if (i<length(levs)) {
json <- paste0(json,",")
}
}
options(useFancyQuotes = op)
json <- paste0(json,"]}")
}
#' vt_export_json
#'
#' exports a node to suitable json required by voronoi javascript function
#'
#' @param node a Node object generated by \code{\link{vt_create_node}} or returned
#' from \code{\link{vt_add_nodes}}
#' @param file path where the json should be written to, if \code{NULL}, the json is returned as
#' a character
#'
#' @return NULL or a character vector
#' @export
#' @seealso vt_create_node vt_add_nodes
#' @examples
#' n <- vt_testdata()
#' vt_export_json(n)
#' vt_export_json(n, file=tempfile())
vt_export_json <- function(node, file=NULL) {
stopifnot("Node" %in% class(node))
stopifnot("R6" %in% class(node))
json <- encodeString(vt_make_json(node))
if (is.null(file)) {
return(json)
}
cat("writing json to",dQuote(file),"\n")
cat(json, file=file)
return(invisible(NULL))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.