首页 > 解决方案 > 漂亮地打印 JSON 到 R 控制台?

问题描述

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

我正在尝试在 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

标签: rjson

解决方案


您可以使用以下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%"
                    }
                ]
            }
        ]
    },
...

推荐阅读