我正在使用Google的go-jsonnet库来评估一些jsonnet文件。
我有一个函数,如下所示,它呈现一个Jsonnet文档:
// Takes a list of jsonnet files and imports each one and mixes them with "+"
func renderJsonnet(files []string, param string, prune bool) string {
// empty slice
jsonnetPaths := files[:0]
// range through the files
for _, s := range files {
jsonnetPaths = append(jsonnetPaths, fmt.Sprintf("(import '%s')", s))
}
// Create a JSonnet VM
vm := jsonnet.MakeVM()
// Join the slices into a jsonnet compat string
jsonnetImport := strings.Join(jsonnetPaths, "+")
if param != "" {
jsonnetImport = "(" + jsonnetImport + ")" + param
}
if prune {
// wrap in std.prune, to remove nulls, empty arrays and hashes
jsonnetImport = "std.prune(" + jsonnetImport + ")"
}
// render the jsonnet
out, err := vm.EvaluateSnippet("file", jsonnetImport)
if err != nil {
log.Panic("Error evaluating jsonnet snippet: ", err)
}
return out
}此函数当前返回一个字符串,因为jsonnet EvaluateSnippet函数返回一个字符串。
我现在要做的是使用格-佩蒂森库呈现这个结果JSON。但是,因为我正在输入的JSON是一个字符串,所以它没有正确地呈现。
所以,有些问题:
发布于 2018-06-29 09:56:57
我是否可以将返回的JSON字符串转换为JSON类型,而无需事先知道如何将其编组为
是。这很简单:
var jsonOut interface{}
err := json.Unmarshal([]byte(out), &jsonOut)
if err != nil {
log.Panic("Invalid json returned by jsonnet: ", err)
}
formatted, err := prettyjson.Marshal([]byte(jsonOut))
if err != nil {
log.Panic("Failed to format jsonnet output: ", err)
}更多信息在这里:5。
是否有一个选项,函数或方法,我在这里错过了,使这更容易?
是。go-prettyjson库有一个Format函数,它为您解压缩:
formatted, err := prettyjson.Format([]byte(out))
if err != nil {
log.Panic("Failed to format jsonnet output: ", err)
}我能以其他方式以一种漂亮的方式呈现json吗?
取决于你对漂亮的定义。Jsonnet通常在一条单独的行上输出对象的每个字段和每个数组元素。这通常被认为是很好的打印(而不是把所有的东西放在同一行上,用最小的空格来节省几个字节)。我想这对你来说还不够好。你可以用jsonnet写你自己的显能者,它可以根据你的喜好格式化(参见std.manifestJson作为一个例子)。
https://stackoverflow.com/questions/51091711
复制相似问题