← 中文资源

简体中文版本

MarshalIndent 缩进与 Compact 压平 JSON

json.MarshalIndent 用自定义缩进输出人类可读的 JSON,json.Marshal 输出单行紧凑形式,json.Compact 把已缩进的文档压回一行;map 键编码时自动排序。

阅读英文原文

实现说明

MarshalIndent 缩进与 Compact 压平 JSON的核心是函数 main。 2 处 err != nil 分支都调用 panic(err)——第一个失败就地终止程序,而不是带着坏状态继续跑。

使用要点

  • 失败路径是 panic(err)——没有可检查的错误返回值,示例里也没有任何恢复机制。
  • 每一步打印都带着自己的标签:compacted:。

常见问题

错误是如何上报的?

以中止方式上报:2 处 err != nil 分支都调用 panic(err),失败在发生地直接终止程序。

运行「MarshalIndent 缩进与 Compact 压平 JSON」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 compacted: 这类标签。

核心语句

if err != nil {
	panic(err)
}

代码示例

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func main() {
	// Map keys are sorted at encoding time: active / name / roles regardless of insertion order
	payload := map[string]any{
		"name":  "ada",
		"roles": []string{"admin", "dev"},
		"active": true,
	}

	// MarshalIndent: multi-line indented output with a customizable prefix and indent string
	pretty, err := json.MarshalIndent(payload, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(pretty))

	// Marshal: single-line compact output for logs and transport
	oneline, _ := json.Marshal(payload)
	fmt.Println(string(oneline))

	// json.Compact squeezes an already-indented document back to one line, dropping extra whitespace
	buf := new(bytes.Buffer)
	if err := json.Compact(buf, pretty); err != nil {
		panic(err)
	}
	fmt.Println("compacted:", buf.String())
}