#r #json
#r #json
Вопрос:
Есть ли способ pretty-print JSON в консоли R?
Я пытаюсь прочитать JSON в консоли R, и было бы намного проще, если бы он печатался уже отформатированным / с отступом. Я попробовал два использования 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:
Вы можете использовать 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%"
}
]
}
]
},
...