2

我使用这样的函数toJSON来创建一个json:

data<-toJSON(list("tablename"= unbox("test.csv"),
                  "header" = header_df,
                  "data" = test1
))

结果如下:

数据

{"tablename":"test.csv","header":["PassengerId","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"],"data":[["892","3","Kelly, Mr. James","male","34.5","0","0","330911","7.8292","","Q"]]}

问题是它为PassengerIDAge数字添加了双引号。如果我手动将 JSON 修改为:

data<-'{"tablename":"test.csv","header":["PassengerId","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"],"data":[[892,"3","Kelly, Mr. James","male",34.5,"0","0","330911","7.8292","","Q"]]}'

然后它工作正常。创建 JSON 时如何删除 JSON 中某些元素的双引号?

您可以在此处找到输入数据:

嗨,你可以在这里找到它链接我使用以下加载它

test <- read.csv("~/Titanic R/test.csv")
header_df<-names(test)
test<-test[1,]
test1<-as.matrix(test)
4

1 回答 1

1

好吧,部分问题是您在这样做时会丢失正确的数据类as.matrix;将所有内容转换为字符值。然后 R 不再记得什么是数字。最好避免这一步。

要获得您想要的结果,您需要一个未命名、未装箱的混合类型列表。这是您的数据的示例

test <- read.csv("~/../Downloads/test.csv", stringsAsFactors=F)

header_df<-names(test)
test<-test[1,]

library(jsonlite)
data<-toJSON(list("tablename"= unbox("test.csv"),
                  "header" = header_df,
                  "data" = Map(unbox, unname(as.list(test)))
))

data
# {"tablename":"test.csv","header":["PassengerId","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"],"data":[892,3,"Kelly, Mr. James","male",34.5,0,0,"330911",7.8292,"","Q"]} 

根据您的评论,如果您有不止一行数据,则此策略应该有效(使用magtrittr库使事情变得更容易)

test <- read.csv("~/../Downloads/test.csv", stringsAsFactors=F)    
header_df<-names(test)

library(magrittr)
tomixedlist <- . %>% unname %>% lapply(unbox)
dx <- split(test, 1:nrow(test)) %>% lapply(tomixedlist) %>% unname

library(jsonlite)
data<-toJSON(list("tablename"= unbox("test.csv"),
                  "header" = header_df,
                  "data" = dx
))
于 2015-03-19T19:18:20.110 回答