encoding a JSON expression from R with jsonlite or something else

邮差的信 提交于 2019-12-06 05:33:47

with jsonlite, you can do as follows:

z <- fromJSON(y, simplifyDataFrame = F)
toJSON(z, auto_unbox=T)

In addition, consider following case where last c element is ["D"]:

y2 <- '[{"a":1, "b":"select", "c":["A", "B", "C"]}, 
        {"a":2, "b":"text"}, 
        {"a":3, "b":"select", "c":["D"]}]'

z2 <- fromJSON(y2, simplifyDataFrame = F)
toJSON(z2, auto_unbox=T)

Result is this:

[{"a":1,"b":"select","c":["A","B","C"]},
 {"a":2,"b":"text"},
 {"a":3,"b":"select","c":"D"}]

This can be a trouble because the last c element is "D" not ["D"].

To prevent this, don's use auto_unbox. Use unbox carefully as follows:

z2 <- fromJSON(y2, simplifyDataFrame = F)
for(i in 1:length(z2)){
  z2[[i]][[1]] <- unbox(z2[[i]][[1]])
  z2[[i]][[2]] <- unbox(z2[[i]][[2]])
}
toJSON(z2)
NicE

If you need to have a data frame to calculate things, you could do (the rmNullObs function is from here):

z <- fromJSON(y)

is.NullOb <- function(x) is.null(x) | all(sapply(x, is.null))

## Recursively step down into list, removing all such objects 
rmNullObs <- function(x) {
  x <- Filter(Negate(is.NullOb), x)
  lapply(x, function(x) if (is.list(x)) rmNullObs(x) else x)
}    

z_list <- rmNullObs(as.list(as.data.frame(t(z))))
toJSON(unname(z_list), auto_unbox=T)

This converts the dataframe to a list, removes the NULL, and converts back to JSON.

If you don't need the dataframe, see @skwon's answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!