将嵌套的JSON解析为R中的数据框架

时间:2014-12-11 18:36:52

标签: json r

我遇到了一个非常讨厌的嵌套JSON。

格式是这样的

{
  "matches": [
    {
      "matchId": 1,
      "region": "BR",
      "participants": [
        {
          "participantId": 0,
          "teamId": 200,
         "stats": {
            "winner": true,
            "champLevel": 16,
            "item0": 3128,
             }
         {
      "matchId": 2,
      "region": "BR",
      "participants": [
        {
          "participantId": 0,
          "teamId": 201,
         "stats": {
            "winner": false,
            "champLevel": 18,
            "item0": 3128,
            "item1": 3157,
            "item1": 3158,
             }

正如您在第二场比赛中所看到的,项目数量增加了,但在数据框架中第一行将具有相同的列:

MatchId  region ... stats.winner stats.champLevel stats.item0 stats.item1 stats.item2  
1         BR          TRUE         16                 3128          1       BR
1         BR          TRUE         16                 3128          3157     3158

看第一行小于第二行,所以R回收值......

如果您想要完整的数据,可以在以下位置获取: http://pastebin.com/HQDf2ase

我如何将json解析为data.frame:

json.matchData <- fromJSON(file="file.json"))

取消列出Json的元素并将其转换为数据框

matchData.i <- lapply(json.matchData$matches, function(x){ unlist(x)})

转换为数据框

matchData <- do.call("rbind", matchData.i)
matchData <- as.data.frame(matchData)

但是数据帧搞砸了,因为有些字段应该是NA但却填充了错误的值。

1 个答案:

答案 0 :(得分:4)

我认为使用plyr rbind.fill()函数会对此有所帮助。这个怎么样

library(plyr)
matchData <- rbind.fill(lapply(matchData.i, 
    function(x) do.call("data.frame", as.list(x))
))

lapply()位是将中间列表转换为rbind.fill所需的data.frames。

相关问题