有没有办法在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
您可以使用以下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%"
}
]
}
]
},
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句