Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

R convert dataframe to JSON

I have a dataframe that I'd like to convert to json format:

my data frame called res1:

library(rjson)

structure(list(id = c(1, 2, 3, 4, 5), value = structure(1:5, .Label = c("server1", 
"server2", "server3", "server4", "server5"), class = "factor")), .Names = c("id", 
"value"), row.names = c(NA, -5L), class = "data.frame")

when I do:

toJSON(res1)

I get this:

{"id":[1,2,3,4,5],"value":["server1","server2","server3","server4","server5"]}

I need this json output to be like this, any ideas?

[{"id":1,"value":"server1"},{"id":2,"value":"server2"},{"id":3,"value":"server3"},{"id":4,"value":"server4"},{"id":5,"value":"server5"}]
question from:https://stackoverflow.com/questions/25550711/r-convert-dataframe-to-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about

library(rjson)
x <- toJSON(unname(split(res1, 1:nrow(res1))))
cat(x)
# [{"id":1,"value":"server1"},{"id":2,"value":"server2"},
# {"id":3,"value":"server3"},{"id":4,"value":"server4"},
# {"id":5,"value":"server5"}]

By using split() we are essentially breaking up the large data.frame into a separate data.frame for each row. And by removing the names from the resulting list, the toJSON function wraps the results in an array rather than a named object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...