Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R jsonlite: create JSON data in a specific format

Tags:

json

r

jsonlite

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
like image 818
Fisseha Berhane Avatar asked Dec 19 '25 06:12

Fisseha Berhane


1 Answers

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"
        }
    }
]
like image 161
cccmir Avatar answered Dec 21 '25 21:12

cccmir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!