如何使用Go漂亮地打印JSON? [英] How can I pretty-print JSON using Go?

查看:973
本文介绍了如何使用Go漂亮地打印JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道在Go中漂亮地打印JSON输出的简单方法吗?

股票 http://golang.org/pkg/encoding/json/ 软件包似乎没有包括这个功能(编辑:它,看到接受的答案)和一个快速的谷歌没有什么明显的。



我正在寻找的用途都很漂亮 - 打印 json的结果。 Marshal 并且只是从任何地方格式化完整的JSON字符串,所以为了调试目的而更容易阅读。

通过漂亮打印,我假设你的意思是缩进,就像这样

  {
data:1234
}

而不是

  {data:1234} 

最简单的方法这是与 MarshalIndent ,这会让你指定h你希望它通过 indent 参数缩进。因此, json.MarshalIndent(data,)将使用四个空格进行缩进。


Does anyone know of a simple way to pretty-print JSON output in Go?

The stock http://golang.org/pkg/encoding/json/ package does not seem to include functionality for this (EDIT: it does, see accepted answer) and a quick google doesn't turn up anything obvious.

Uses I'm looking for are both pretty-printing the result of json.Marshal and just formatting a string full of JSON from wherever, so it's easier to read for debug purposes.

解决方案

By pretty-print, I assume you mean indented, like so

{
    "data": 1234
}

rather than

{"data":1234}

The easiest way to do this is with MarshalIndent, which will let you specify how you would like it indented via the indent argument. Thus, json.MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.

这篇关于如何使用Go漂亮地打印JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆