fx/pkg/json/stringify.go

52 lines
796 B
Go
Raw Normal View History

2022-04-17 20:57:12 +00:00
package json
2022-03-29 16:13:41 +00:00
import (
"fmt"
2022-04-17 20:57:12 +00:00
. "github.com/antonmedv/fx/pkg/dict"
2022-03-29 16:13:41 +00:00
)
2022-04-17 20:57:12 +00:00
func Stringify(v interface{}) string {
2022-03-29 16:13:41 +00:00
switch v.(type) {
case nil:
return "null"
case bool:
if v.(bool) {
return "true"
} else {
return "false"
}
2022-04-17 20:57:12 +00:00
case Number:
return v.(Number).String()
2022-03-29 16:13:41 +00:00
case string:
return fmt.Sprintf("%q", v)
2022-04-17 20:57:12 +00:00
case *Dict:
2022-03-29 16:13:41 +00:00
result := "{"
2022-04-17 20:57:12 +00:00
for i, key := range v.(*Dict).Keys {
line := fmt.Sprintf("%q", key) + ": " + Stringify(v.(*Dict).Values[key])
if i < len(v.(*Dict).Keys)-1 {
2022-04-14 12:30:36 +00:00
line += ","
2022-03-29 16:13:41 +00:00
}
result += line
}
return result + "}"
2022-04-17 20:57:12 +00:00
case Array:
2022-03-29 16:13:41 +00:00
result := "["
2022-04-17 20:57:12 +00:00
for i, value := range v.(Array) {
line := Stringify(value)
if i < len(v.(Array))-1 {
2022-04-14 12:30:36 +00:00
line += ","
2022-03-29 16:13:41 +00:00
}
result += line
}
return result + "]"
default:
return "unknown type"
}
}