Convert json file to R object in R

966 views Asked by At

I am trying to convert a json file in R. The format of the data is as follows:

{
"id": "xyz",
"root": {
"author": {
"name": "xyz",
"email": "[email protected]",
"date": "2014-10-08T00:10:30Z"
},
"authorer": {
"name": "xyz",
"email": "[email protected]",
"date": "2014-10-08T00:11:30Z"
 },
"message": "This a test json",
"root": {
"id": "xyz1",
"url": "xyz"
},
"url": "xyz",
"message_count": 0
},
"url": "xyz",
"html_url": "xyz",
"comments_url": "abc",
"author": null,
"authorer": null,
"parent": [
{
"id": "xyz3",
"url": "xyz",
"html_url": "xyz"
}
]
}

After this a similar row begins, with {having the same formatted text }This is the code I wrote in R

install.packages("rjson")
library(rjson)
df <- fromJSON(paste(readLines("file.json"), collapse=""))
View(df)

I was wondering how do make this file readable in R? I wanted to see them as columns like this:

id  root/author/name    root/author/email   root/author/date    root/authorer/name  

Refer to here: http://konklone.io/json/?id=dfeae96a607c7541b8fe (of how the input and output should look like).

I have provided a new link here for two rows: http://konklone.io/json/?id=3b01a02e17ec4fde3357

Thanks a lot

1

There are 1 answers

5
sckott On BEST ANSWER

Is this what you want:

json <- '{
  "id": "xyz",
  "root": {
    "author": {
      "name": "xyz",
      "email": "[email protected]",
      "date": "2014-10-08T00:10:30Z"
    },
    "authorer": {
      "name": "xyz",
      "email": "[email protected]",
      "date": "2014-10-08T00:11:30Z"
    },
    "message": "This a test json",
    "root": {
      "id": "xyz1",
      "url": "xyz"
    },
    "url": "xyz",
    "message_count": 0
  },
  "url": "xyz",
  "html_url": "xyz",
  "comments_url": "abc",
  "author": null,
  "authorer": null,
  "parent": [
    {
      "id": "xyz3",
      "url": "xyz",
      "html_url": "xyz"
    }
  ]
}'

out <- jsonlite::fromJSON(json)
out[vapply(out, is.null, logical(1))] <- "none"
data.frame(out, stringsAsFactors = FALSE)[,1:5]

   id root.author.name root.author.email     root.author.date root.authorer.name
1 xyz              xyz       [email protected] 2014-10-08T00:10:30Z                xyz