Skip to content

Instantly share code, notes, and snippets.

@vst
Created November 23, 2011 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vst/1388190 to your computer and use it in GitHub Desktop.
Save vst/1388190 to your computer and use it in GitHub Desktop.
Marshalling between xts objects and JSON representations of xts objects.
##' Declares the generic as.json method.
##'
##' @param x the object to be marshalled to JSON
##' @param ... extra arguments to the actual function
##' @return a JSON representation of the consumed object.
##' @export
as.json = function (x, ...) {
UseMethod("as.json")
}
##' Declares the as.json method for xts instances
##'
##' @param x the xts object to be marshalled to JSON
##' @param ... extra arguments to the data.frame
##' @return a JSON representation of the consumed xts object.
##' @export
as.json.xts = function (x, ...) {
## Prepare the data frame first:
retval = data.frame(cbind(Index=as.character(index(x)), coredata(x)), ...)
## Remove the row names:
rownames(retval) = NULL
## Done, return the JSON:
return(toJSON(as.list(retval)))
}
##' Consumes a JSON string and returns an xts instance.
##'
##' @param x the JSON representation of the xts instance. The first
##' column is meant to be the index of the xts instance to be
##' constructed.
##' @param ... extra parameters to xts function.
##' @return the xts instance.
##' @export
xtsFromJSON = function (x, ...) {
## Get the list:
retval = as.data.frame(fromJSON(x))
## Construct and return xts instance:
return(xts(retval[,-1], order.by=as.POSIXct(retval[,1]), ...))
}
@vanhumbeecka
Copy link

Just what i was looking for!
Now I can convert my xts object to a consumable json for javascript charting libraries.

Thanks

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