简体   繁体   中英

Writing an R dataframe into an infogram readable JSON file

I'm trying to write a dataframe to a JSON format that infogram can recognise, to automate live updates. I've been using R and the jsonlite package.

For example:

df <- data.frame(X = c(1,2,3),
                 Y = c(5,7,8))
df

#  X Y
#1 1 5
#2 2 7
#3 3 8

I've come up with:

require(jsonlite)

rbind(as.matrix(t(names(df))), 
      as.matrix(df)) %>% 
  toJSON(pretty = T) # or write_json(filename, pretty = T) to write straight to file

Which results in:

[
  ["X", "Y"],
  ["1", "5"],
  ["2", "7"],
  ["3", "8"]
] 

The desired format is essentially the above but enclosed in an extra pair of square brackets (note the first array consists of column headings, then each subsequent array is an observation).

[[
  ["X", "Y"],
  ["1", "5"],
  ["2", "7"],
  ["3", "8"]
]]

Is there an easy way to achieve this? Thanks

require(jsonlite)

## The data.frame
df <- data.frame(X = c(1,2,3),
                 Y = c(5,7,8))

Now you could modify your object to be a list then you'll get the same list item in your json output:

mat <- list(rbind(as.matrix(t(names(df))), as.matrix(df)))

now with the extra bracket you want:

toJSON(mat, pretty = T)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM