Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Created October 29, 2013 20:28
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 ramnathv/7222006 to your computer and use it in GitHub Desktop.
Save ramnathv/7222006 to your computer and use it in GitHub Desktop.
Data Frame to JSON ala Pandas
to_json = function(df, orient = "columns", json = T){
dl = as.list(df)
dl = switch(orient,
columns = dl,
records = do.call('zip_vectors_', dl),
values = do.call('zip_vectors_', setNames(dl, NULL))
)
if (json){
dl = rjson::toJSON(dl)
}
return(dl)
}
zip_vectors_ = function(..., names = F){
x = list(...)
y = lapply(seq_along(x[[1]]), function(i) lapply(x, pluck_(i)))
if (names) names(y) = seq_along(y)
return(y)
}
pluck_ = function (element){
function(x) x[[element]]
}
df = data.frame(
x = c(1, 2),
y = c('a', 'b')
)
to_json(df, orient = 'columns')
# {"x":[1,2],"y":["a","b"]}
to_json(df, orient = 'records')
# [{"x":1,"y":"a"},{"x":2,"y":"b"}]
to_json(df, orient = 'values')
# [[1,"a"],[2,"b"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment