将json文件转换为R中的R对象

时间:2014-11-12 17:10:56

标签: json r rjson

我正在尝试在R中转换json文件。数据的格式如下:

{
"id": "xyz",
"root": {
"author": {
"name": "xyz",
"email": "xyx@xyz.org",
"date": "2014-10-08T00:10:30Z"
},
"authorer": {
"name": "xyz",
"email": "xyx@xyz.org",
"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"
}
]
}

在此之后,类似的行开始,{具有相同的格式化文本}这是我在R中编写的代码

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

我想知道如何在R中使这个文件可读?我希望将它们看作这样的列:

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

请参阅此处:http://konklone.io/json/?id=dfeae96a607c7541b8fe(输入和输出应如何显示)。

我在这里为两行提供了一个新链接:http://konklone.io/json/?id=3b01a02e17ec4fde3357

非常感谢

1 个答案:

答案 0 :(得分:1)

这就是你想要的:

json <- '{
  "id": "xyz",
  "root": {
    "author": {
      "name": "xyz",
      "email": "xyx@xyz.org",
      "date": "2014-10-08T00:10:30Z"
    },
    "authorer": {
      "name": "xyz",
      "email": "xyx@xyz.org",
      "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       xyx@xyz.org 2014-10-08T00:10:30Z                xyz