math
math

Reputation: 2022

how to create a nested array of objects from a dataframe

I would like to get a nested array of objects (JSON) using the jsonlite package in R from a data.frame format. Let me give an example

library(jsonlite)
time <- c(1,1,2,2)
ps <- c("p1","p2","p1","p2")
v1 <- c(5,6,7,8)
v2 <- c(10,11,12,13)
df <- data.frame(ps, v1,v2)
toJSON(df)

here df is a data frame in R and I get a array of objects in Json format:

[{"ps":"p1","v1":5,"v2":10},
 {"ps":"p2","v1":6,"v2":11},
 {"ps":"p1","v1":7,"v2":12},
 {"ps":"p2","v1":8,"v2":13}] 

However, I would like to achieve the following output, where essentially I have a nested structure. Adding something like another grouping argument (time) here, df in a long format looks like

df2 <- data.frame(time,ps, v1,v2)

which is

df2
  time ps v1 v2
1    1 p1  5 10
2    1 p2  6 11
3    2 p1  7 12
4    2 p2  8 13

My final output I would like to achieve (in Json) format is

[{
  "time": "1"
  "all_ps":[
    {
      "ps":"p1",
      "v1":5,
      "v2":10    
    },
    {
      "ps":"p2",
      "v1":6,
      "v2":11
    }]
  },
  {
    "time": "2"
    "all_ps":[
  {
    "ps":"p1",
    "v1":5,
    "v2":10    
  },
  {
    "ps":"p2",
    "v1":6,
    "v2":11
  }]  
  }
 ]

where all_ps is like an additional structure or grouping. This all_ps is given but I don't know how to add it to the data frame to obtian the desired output. How can I achieve this in R using jsonlite?

Upvotes: 1

Views: 895

Answers (2)

chinsoon12
chinsoon12

Reputation: 25225

Another way of splitting up your data frame without knowing the contents in the time column:

library(jsonlite)
ansLs <- lapply(split(df2, df2$time), 
    function(x) list(time=as.character(x$time[1]),  all_ps=x[-1]))
toJSON(unname(ansLs), auto_unbox = TRUE)

Upvotes: 1

amatsuo_net
amatsuo_net

Reputation: 2448

This works:

library(magrittr)
library(jsonlite)
lapply(as.list(1:2), function(x) list(time = as.character(x), 
                                      "all_ps" = df[time == x, ])) %>%
    toJSON(auto_unbox = TRUE)

Upvotes: 1

Related Questions