1

Say I have the following dataframes:

df1 <- data.frame(Name = c("Harry","George"), color=c("#EA0001", "#EEEEEE"))

    Name   color
1  Harry #EA0001
2 George #EEEEEE


df.details <- data.frame(Name = c(rep("Harry",each=3), rep("George", each=3)),
                         age=21:23,
                         total=c(14,19,24,1,9,4)
                         )


    Name age total
1  Harry  21    14
2  Harry  22    19
3  Harry  23    24
4 George  21     1
5 George  22     9
6 George  23     4

I know how to convert each df to json like this:

library(jsonlite)
toJSON(df.details)
[{"Name":"Harry","age":21,"total":14},{"Name":"Harry","age":22,"total":19},{"Name":"Harry","age":23,"total":24},{"Name":"George","age":21,"total":1},{"Name":"George","age":22,"total":9},{"Name":"George","age":23,"total":4}] 

However, I am looking to get the following structure to my JSON data:

{
"myjsondata": [

{
"Name": "Harry", 
"color": "#EA0001", 
"details": [
  {
    "age": 21, 
    "total": 14
  }, 
  {
    "age": 22, 
    "total": 19
  }, 
  {
    "age": 23, 
    "total": 24
  }
  ]
}, 
{
  "Name": "George", 
  "color": "#EEEEEE", 
  "details": [
    {
      "age": 21, 
      "total": 1
    }, 
    {
      "age": 22, 
      "total": 9
    }, 
    {
      "age": 23, 
      "total": 4
    }
    ]
}

]
}

I think the answer may be in how I store the data in a list in R before converting, but not sure.

1 Answer 1

3

Try this format:

df1$details <- split(df.details[-1], df.details$Name)[df1$Name]
df1
#    Name   color                details
#1  Harry #EA0001 21, 22, 23, 14, 19, 24
#2 George #EEEEEE    21, 22, 23, 1, 9, 4

toJSON(df1)
#[{
#"Name":"Harry",
#"color":"#EA0001",
#"details":[
#  {"age":21,"total":14},
#  {"age":22,"total":19},
#  {"age":23,"total":24}]},
#{
#"Name":"George",
#"color":"#EEEEEE",
#"details":[
#  {"age":21,"total":1},
#  {"age":22,"total":9},
#  {"age":23,"total":4}]}
#] 
Sign up to request clarification or add additional context in comments.

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.