Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add print.tbl_json method #13

Open
jeremystan opened this issue Sep 19, 2014 · 2 comments
Open

Add print.tbl_json method #13

jeremystan opened this issue Sep 19, 2014 · 2 comments

Comments

@jeremystan
Copy link

Should work like print.tbl_df in dplyr and only print the two N rows (with ...s). But should also print the JSON, and use prettify(toJSON()) to do so.

@jeremystan
Copy link
Author

This is more painful than it seems, given jsonlite interprets scalars as arrays

'{"k":"v"}' %>% fromJSON %>% toJSON == '{"k":["v"]}'
# [1] true

Also, not clear how best to format the JSON (prettify or minify? append as column or print below?)

@jeremystan
Copy link
Author

This was a (somewhat sloppy) attempt:

print.tbl_json <- function(x, ..., n = NULL) {

  # Compute n consistent wtih dplyr::trunc_mat
  rows <- nrow(x)
  if (is.null(n)) {
    if (is.na(rows) || rows > getOption("dplyr.print_max")) {
      n <- getOption("dplyr.print_min")
    } else {
      n <- rows
    }
  }

  # Consistent with dplyr::tbl_df
  cat("tbl_json data frame ", dim_desc(x), "\n", sep = "")
  cat("\n")
  trunc_mat(x, n = n)

  # Print json formatting
  cat("\nJSON attribute:\n\n")
  take <- if (rows > n) n + 1 else n
  json <- attr(x, "JSON")[sequence(take)]
  json_char <- vapply(lapply(json, toJSON), minify, character(1))

  jdf <- data.frame(
    JSON = json_char,
    stringsAsFactors = FALSE)
  trunc_mat(jdf, n = n)

}

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

No branches or pull requests

1 participant