直接从JSON文件获取数据帧?

时间:2011-06-29 20:12:00

标签: json r

首先,让我感谢所有为Stackoverflow和R做出贡献的人!我是那些不太擅长编程的R用户之一,但是勇敢地尝试将它用于工作,所以下面的问题可能是微不足道的......

这是问题所在。我需要将JSON格式的文件导入R:

# library(plyr)
# library(RJSONIO)
# lstJson <- fromJSON("JSON_test.json")        #This is the file I read
# dput(lstJson)                                              #What I did to get the txtJson below, for the benefit of testing.

txtJson <- structure(list(version = "1.1", result = structure(list(warnings = structure(list(), class = "AsIs"), fields = list(structure(list(info = "", rpl = 15, name = "time", type = "timeperiod"), .Names = c("info", "rpl", "name", "type")), structure(list(info = "", name = "object", type = "string"), .Names = c("info", "name", "type")), structure(list(info = "Counter1", name = "Counter1", type = "int"), .Names = c("info", "name", "type")), structure(list( info = "Counter2", name = "Counter2", type = "int"), .Names = c("info", "name", "type"))), timeout = 180, name = NULL, data = list( list(list("2011-05-01 17:00", NULL), list("Total", NULL), list(8051, NULL), list(44, NULL)), list(list("2011-05-01 17:15", NULL), list("Total", NULL), list(8362, NULL), list( 66, NULL))), type = "AbcDataSet"), .Names = c("warnings", "fields", "timeout", "name", "data", "type"))), .Names = c("version", "result"))

dfJson <- ldply(txtJson, data.frame)  

我需要的是与此类似的数据框:

time  object  Counter1  Counter2  
2011-05-01 17:00  Total  8051  44  
2011-05-01 17:15  Total  8362  66 

但我得到了

"Error in data.frame("2011-05-01 17:00", NULL, check.names = FALSE, stringsAsFactors = TRUE) : 
  arguments imply differing number of rows: 1, 0"

如果我使用lstJson,我会得到同样的错误。

我不确定RJSONIO是否应该“足够智能”来解析这样的文件,或者我是否必须手动读取文件的第一行,设置列类型等等。我不使用CSV是因为我想“自动”以日期格式等方式获取日期。

谢谢, /克里斯

1 个答案:

答案 0 :(得分:6)

查看txtJson的结构,你会发现所有有用的位都在txtJson $ result $ data中:

> sapply( txtJson$result$data, unlist )
     [,1]               [,2]              
[1,] "2011-05-01 17:00" "2011-05-01 17:15"
[2,] "Total"            "Total"           
[3,] "8051"             "8362"            
[4,] "44"               "66"              
> t(sapply( txtJson$result$data, unlist ))
     [,1]               [,2]    [,3]   [,4]
[1,] "2011-05-01 17:00" "Total" "8051" "44"
[2,] "2011-05-01 17:15" "Total" "8362" "66"
> as.data.frame(t(sapply( txtJson$result$data, unlist )) )
                V1    V2   V3 V4
1 2011-05-01 17:00 Total 8051 44
2 2011-05-01 17:15 Total 8362 66

在将这些作为未列出的向量获取然后传递给'as.data.frame'的过程中,它们现在都是类'因子',因此可能需要额外的努力来重新分类()这些值。您可以改为使用:

data.frame(t(sapply( txtJson$result$data, unlist )) ,stringsAsFactors=FALSE)

他们都是'性格'

就导入CSV文件而言,read.table()的colClasses参数将接受“POSIXlt”或“POSIXct”作为已知类型。我相信规则是必须有。 _ 方法。这是一个最小的例子:

> read.table(textConnection("2011-05-01 17:00"), sep=",", colClasses="POSIXct")
                   V1
1 2011-05-01 17:00:00