代码之家  ›  专栏  ›  技术社区  ›  stevec Zxeenu

漂亮的打印JSON到R控制台?

  •  1
  • stevec Zxeenu  · 技术社区  · 4 年前

    有没有办法在R控制台中漂亮地打印JSON?

    cat() 观察到了新的行字符,但没有缩进。

    JSON示例:

    library(tidyverse)
    library(jsonlite)
    require(RJSONIO)
    
    df <- data.frame(name=c("Holdingcompany","Holdingcompany","company1","company1","company2","company2"),children=c("company1","company2","company4","company3","company5","company6"),info=c("text1","text2","text3","text5","othertext","other_text"),percentage=c("100%","100%","60%","75%","80%","70%"))
    
    makeList<-function(x){
      if(ncol(x)>2){
        listSplit<-split(x[-1],x[1],drop=T)
        lapply(names(listSplit),function(y){list(name=y,children=makeList(listSplit[[y]]))})
      }else{
        lapply(seq(nrow(x[1])),function(y){list(name=x[,1][y],Percentage=x[,2][y])})
      }
    }
    
    # This provides unformatted JSON
    makeList(df) %>% toJSON
    
    # This shows new lines, but not indentation
    makeList(df) %>% toJSON %>% cat
    
    
    1 回复  |  直到 4 年前
        1
  •  5
  •   lroha    4 年前

    你可以使用 prettify() 函数来自 jsonlite :

    library(dplyr)
    library(jsonlite)
    
    makeList(df) %>% 
      toJSON %>% 
      prettify()
    
    [
        {
            "name": "company1",
            "children": [
                {
                    "name": "company3",
                    "children": [
                        {
                            "name": "text5",
                            "Percentage": "75%"
                        }
                    ]
                },
                {
                    "name": "company4",
                    "children": [
                        {
                            "name": "text3",
                            "Percentage": "60%"
                        }
                    ]
                }
            ]
        },
    ...