1

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask you how I can tweak the code such that numerical values won't be in double quotes after calling toJson? I.e. "v2": 11 and not "v2": "11"
Do not have access to R right now. Was the data.frame already in the correct data type? If it already is, you might need to construct your all_ps explicitly.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.