3

I want to create JSON data using R's jsonlite package to load to DynamoDB using Python. I want the data to be in the structure shown below. How can I create this in R? I tried creating a data frame where one of the columns is a list and change the data frame to json but the result is not in the required format. I also tried a converting a list which contains a list, but the structure of the output json is not what I want.

[
{
    "ID": 100,
    "title": "aa",
    "more": {
      "interesting":"yes",
      "new":"no",
      "original":"yes"
    }
},

{
    "ID": 110,
    "title": "bb",
    "more": {
      "interesting":"no",
      "new":"yes",
      "original":"yes"
    }
},

{
    "ID": 200,
    "title": "cc",
    "more": {
      "interesting":"yes",
      "new":"yes",
      "original":"no"
    }
  }
]

Here is my sample data and what I tried:

library(jsonlite)

ID=c(100,110,200)
Title=c("aa","bb","cc")
more=I(list(Interesting=c("yes","no","yes"),new=c("no","yes","yes"),original=c("yes","yes","no")))

 a=list(ID=ID,Title=Title,more=more)
 a=toJSON(a)
 write(a,"temp.json")  # this does not give the structure I want
Fisseha Berhane
  • 2,533
  • 4
  • 30
  • 48

1 Answers1

7

this will produce what you need:

library(jsonlite)

ID=c(100,110,200)
Title=c("aa","bb","cc")

df <- data.frame(ID, Title)
more=data.frame(Interesting=c("yes","no","yes"),new=c("no","yes","yes"),original=c("yes","yes","no"))
df$more <- more

toJSON(df)

output:

[{
        "ID": 100,
        "Title": "aa",
        "more": {
            "Interesting": "yes",
            "new": "no",
            "original": "yes"
        }
    }, {
        "ID": 110,
        "Title": "bb",
        "more": {
            "Interesting": "no",
            "new": "yes",
            "original": "yes"
        }
    }, {
        "ID": 200,
        "Title": "cc",
        "more": {
            "Interesting": "yes",
            "new": "yes",
            "original": "no"
        }
    }
]
cccmir
  • 953
  • 6
  • 12
  • pasting and running your code in my Rstudio produces the folllowing: > toJSON(df) [1] "{\"ID\":[100,110,200],\"Title\":[\"aa\",\"bb\",\"cc\"],\"more\":{\"Interesting\":[\"yes\",\"no\",\"yes\"],\"new\":[\"no\",\"yes\",\"yes\"],\"original\":[\"yes\",\"yes\",\"no\"]}} why? – chilifan Sep 24 '21 at 11:13