fx/pkg/json/pretty_print.go

72 lines
1.4 KiB
Go
Raw Normal View History

2022-04-17 20:57:12 +00:00
package json
import (
"encoding/json"
"fmt"
"github.com/antonmedv/fx/pkg/dict"
"github.com/antonmedv/fx/pkg/theme"
"strings"
)
func PrettyPrint(v interface{}, level int, theme theme.Theme) string {
ident := strings.Repeat(" ", level)
subident := strings.Repeat(" ", level-1)
2022-04-27 22:02:18 +00:00
switch v := v.(type) {
2022-04-17 20:57:12 +00:00
case nil:
return theme.Null("null")
case bool:
2022-04-27 22:02:18 +00:00
if v {
2022-04-17 20:57:12 +00:00
return theme.Boolean("true")
} else {
return theme.Boolean("false")
}
case json.Number:
2022-04-27 22:02:18 +00:00
return theme.Number(v.String())
2022-04-17 20:57:12 +00:00
case string:
return theme.String(fmt.Sprintf("%q", v))
case *dict.Dict:
2022-04-27 22:02:18 +00:00
keys := v.Keys
2022-04-17 20:57:12 +00:00
if len(keys) == 0 {
return theme.Syntax("{}")
}
output := theme.Syntax("{")
output += "\n"
for i, k := range keys {
key := theme.Key(i, len(keys))(fmt.Sprintf("%q", k))
2022-04-27 22:02:18 +00:00
value, _ := v.Get(k)
2022-04-17 20:57:12 +00:00
delim := theme.Syntax(": ")
line := ident + key + delim + PrettyPrint(value, level+1, theme)
if i < len(keys)-1 {
line += theme.Syntax(",")
}
line += "\n"
output += line
}
return output + subident + theme.Syntax("}")
case []interface{}:
2022-04-27 22:02:18 +00:00
slice := v
2022-04-17 20:57:12 +00:00
if len(slice) == 0 {
return theme.Syntax("[]")
}
output := theme.Syntax("[\n")
2022-04-27 22:02:18 +00:00
for i, value := range v {
2022-04-17 20:57:12 +00:00
line := ident + PrettyPrint(value, level+1, theme)
if i < len(slice)-1 {
line += ",\n"
} else {
line += "\n"
}
output += line
}
return output + subident + theme.Syntax("]")
default:
return "unknown type"
}
}