如何使用encoding/json在Go中生成人类可读的JSON输出
在Go程序中输出JSON(称为“foo”)时,它可能是有益的使结果具有可读性,以便更好地解释。虽然通常通过管道输出来使用 jq 命令行工具来实现此目的,但本文提供了一种使用 Go 内置的编码/json 包的替代解决方案。
encoding/json 包提供了本机支持无需外部工具即可生成缩进的 JSON。通过利用 json.MarshalIndent() 函数或调用 json.Encoder.SetIndent() (自 Go 1.7 起可用),您可以实现所需的结果。
例如,要将映射缩进为可读的 JSON:
m := map[string]interface{}{"id": "uuid1", "name": "John Smith"} data, err := json.MarshalIndent(m, "", " ") if err != nil { panic(err) } fmt.Println(string(data))
或者,您可以将 json.Encoder 与SetIndent():
enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") if err := enc.Encode(m); err != nil { panic(err) }
您还可以使用 json.Indent() 格式化现有的 JSON 字符串:
src := `{"id":"uuid1","name":"John Smith"}` dst := &bytes.Buffer{} if err := json.Indent(dst, []byte(src), "", " "); err != nil { panic(err) } fmt.Println(dst.String())
这些函数中的 prefix 和 indent 参数决定缩进样式。每个新行之前都会有前缀,而每层嵌套都会重复缩进。
通过利用这些方法,您可以轻松地在 Go 中生成人类可读的 JSON,而无需额外的工具或依赖项,从而增强了可读性和JSON 输出的可用性。
以上是如何在 Go 中使 JSON 输出可读?的详细内容。更多信息请关注PHP中文网其他相关文章!

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。

Ingo,替代词Inivuntionsionializatializatializationfunctionsandsingletons.1)customInitializationfunctions hallowexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssementializatizatupsetups.2)单次固定元素限制ininconinconcurrent

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版
中文版,非常好用

记事本++7.3.1
好用且免费的代码编辑器

Dreamweaver Mac版
视觉化网页开发工具