aruizga
aruizga

Reputation: 644

Remove double quotes json created using toJSON

I use the function toJSON like this to create a json:

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

the result is the following:

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"]]}

The problem is that it is adding double quotes for the PassengerID and the Age numbers. If I modify manually the JSON to this:

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"]]}'

then it is working fine. How can I remove the double quotes of some elements in the JSON when creating the JSON?

You can find the input data here:

Hi, you can find it here link I use the following to load it

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

Upvotes: 2

Views: 1344

Answers (1)

MrFlick
MrFlick

Reputation: 206401

Well, part of the problem is that you are loosing the proper data classes when you do as.matrix; that converts everything to a character value. Then R no longer remembers what was numeric. It's best to avoid this step.

To get a result like the one you desire, you need an unnamed, unboxed mixed-type list. Here's an example with your data

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"]} 

Based on your comment, if you have more than one row of data, this strategy should work (using magtrittr library to make things easier)

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
))

Upvotes: 1

Related Questions