RunChiRun
RunChiRun

Reputation: 168

R - convert JSON to desired format

My dataframe currently looks like this:

df$name <- c("Person A","Person B","Person C")
df$count <- c(50,100,150)

Using toJSON from the jsonlite package produces an array that does not preserve the numeric class of the count variable.:

toJSON(as.matrix(df))
[["Person A","50"],["Person B","100"],["Person C","150"]]

I fully recognize this is because converting df to a matrix requires all data to be of the same class. Instead, I would like the classes preserved such that name is preserved as a string and count is preserved as numeric, like so:

[["Person A",50],["Person B",100],["Person C",150]]

For some context, I'd like to be able to feed the JSON output externally to Google Charts (not through googleVis). Suggestions and help are so greatly appreciated- I've tried a number of things and can't quite seem to yield the product I need. Thanks!

Upvotes: 0

Views: 80

Answers (1)

agstudy
agstudy

Reputation: 121568

You should transform your data.frame to a paired list before transforming it to a json string. :

library(RJSONIO) 
## use  cat for better print
cat(toJSON(Map(function(x,y)list(x,y),df$name,df$count)))

[
 [
 "Person A",
    50 
],
[
 "Person B",
   100 
],
[
 "Person C",
   150 
] 
]

Upvotes: 2

Related Questions