Json for DataTables from data.frame using R

时间:2016-04-15 12:38:03

标签: json r

我想从R data.frame创建json文件作为dataTables(link)的输入。

df <- data.frame(RowNames <- c("FirstCol","SecondCol","ThirdCol","FourthCol"),
                                FirstCol <- c(0.1,0,0,0.28),
                                SecondCol <- c(0,0,0.1,0),
                                ThirdCol <- c(0,0,0,0.3),
                                FourthCol <- c(0.28,0,0,0.7))
names(df) <- c("RowNames", "FirstCol", "SecondCol", "ThirdCol", "FourthCol")

期望的输出应该是:

{
    "columns": [
    {"title":"Json for table"},
    { "title": "FirstCol"},
    { "title": "SecondCol"},
    { "title": "ThirdCol"},
    { "title": "FourthCol"}],
"data": [
    ["FirstCol", "0.1", "0", "0", "0.28"],
    ["SecondCol", "0", "0", "0.1", "0"],
    ["ThirdCol", "0", "0", "0", "0.3"],
    ["FourthCol", "0.28", "0", "0", "0.7"]]
}

你知道我怎么能以最简单的方式做到这一点?非常感谢您的任何帮助。

1 个答案:

答案 0 :(得分:0)

我刚刚编写了这个疯狂的函数来从递归列表结构生成JSON:

rlistToJSON <- function(node,indent=0L) {
    if (is.na(indent)) {
        LF <- tab0 <- tab1 <- '';
    } else {
        LF <- '\n';
        tab0 <- paste(collapse='',rep('  ',indent));
        tab1 <- paste(collapse='',rep('  ',indent+1L));
    }; ## end if
    res <- if (is.list(node)) { ## array or hash
        if (is.null(names(node))) { ## array
            if (length(node)==0L) { ## empty array
                '[]'
            } else { ## non-empty array
                paste0(
                    '[',LF,
                    paste(
                        collapse=paste0(',',LF),
                        sapply(seq_along(node),function(i)
                            paste0(
                                tab1,
                                rlistToJSON(node[[i]],indent+1L)
                            )
                        )
                    ),
                    LF,tab0,']'
                )
            }; ## end if
        } else { ## hash
            if (length(node)==0L) { ## empty hash
                '{}'
            } else { ## non-empty hash
                paste0(
                    '{',LF,
                    paste(
                        collapse=paste0(',',LF),
                        sapply(seq_along(node),function(i)
                            paste0(
                                tab1,
                                '"',gsub('(["\\\\])','\\\\\\1',names(node)[i]),'":',
                                rlistToJSON(node[[i]],indent+1L)
                            )
                        )
                    ),
                    LF,tab0,'}'
                )
            }; ## end if
        }; ## end if
    } else if (is.null(node)) { ## null
        'null';
    } else { ## primitive vector
        content <- ifelse(is.na(node),'null',if (is.logical(node)) { ## boolean
            c('false','true')[node+1L]
        } else if (is.numeric(node)) { ## numeric
            node
        } else if (is.character(node)) { ## string
            paste0('"',gsub('(["\\\\])','\\\\\\1',node),'"')
        } else stop(paste0('invalid node type: ',typeof(node),'.'))); ## invalid
        if (!is.null(names(node)))
            content <- paste0('"',gsub('(["\\\\])','\\\\\\1',names(node)),'":',content);
        content <- paste(collapse=',',content);
        if (!is.null(names(node))) {
            paste0('{',content,'}')
        } else if (length(node)==1L) {
            content
        } else {
            paste0('[',content,']');
        }; ## end if
    }; ## end if
    if (!is.na(indent) && indent==0L) paste0(res,LF) else res;
}; ## end rlistToJSON()

随机测试:

cat(rlistToJSON(list()));
## []
cat(rlistToJSON(setNames(list(),character())));
## {}
cat(rlistToJSON(3));
## 3
cat(rlistToJSON(3:4));
## [3,4]
cat(rlistToJSON(list(3)));
## [
##   3
## ]
cat(rlistToJSON(list(3:4,5)));
## [
##   [3,4],
##   5
## ]
cat(rlistToJSON(list(a=3,b=4)));
## {
##   "a":3,
##   "b":4
## }
cat(rlistToJSON(list('a"\\b')));
## [
##   "a\"\\b"
## ]
cat(rlistToJSON(list(letters[1:10],LETTERS[1:10])));
## [
##   ["a","b","c","d","e","f","g","h","i","j"],
##   ["A","B","C","D","E","F","G","H","I","J"]
## ]
cat(rlistToJSON(list(c(T,F),list(c(4.56,1234.34),x=c(a=45,b=5)))));
## [
##   [true,false],
##   {
##     "":[4.56,1234.34],
##     "x":{"a":45,"b":5}
##   }
## ]
cat(rlistToJSON(list(NULL,NULL,c(3,NA,4),'a')));
## [
##   null,
##   null,
##   [3,null,4],
##   "a"
## ]
cat(rlistToJSON(list(NULL,NULL,c(3,NA,4),'a'),NA),'\n');
## [null,null,[3,null,4],"a"]
cat(rlistToJSON(c('a','b"',NA)));
## ["a","b\"",null]
cat(rlistToJSON(c(a='a',b='b"',c=NA)));
## {"a":"a","b":"b\"","c":null}

对于您的数据:

cat(rlistToJSON(list(
    columns=unname(lapply(c('Json for table',names(df)[-1L]),function(x) c(title=x))),
    data=unname(Map(c,names(df)[-1L],df[-1L]))
)));
## {
##   "columns":[
##     {"title":"Json for table"},
##     {"title":"FirstCol"},
##     {"title":"SecondCol"},
##     {"title":"ThirdCol"},
##     {"title":"FourthCol"}
##   ],
##   "data":[
##     ["FirstCol","0.1","0","0","0.28"],
##     ["SecondCol","0","0","0.1","0"],
##     ["ThirdCol","0","0","0","0.3"],
##     ["FourthCol","0.28","0","0","0.7"]
##   ]
## }