我使用像这样的函数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"]]}
问题在于它为PassengerID
和Age
数字添加了双引号。如果我手动将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中某些元素的双引号?
您可以在此处找到输入数据:
嗨,您可以在此处找到link我使用以下内容加载
test <- read.csv("~/Titanic R/test.csv")
header_df<-names(test)
test<-test[1,]
test1<-as.matrix(test)
答案 0 :(得分: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
))