Does anyone know of a simple way to pretty-print JSON output in Go?
I'd like to pretty-print the result of json.Marshal
, as well as formatting an existing string of JSON so it's easier to read.
JSON pretty print by marshaling valueFunction json. MarshalIndent generates JSON encoding of the value with indentation. You can specify a prefix of each JSON line and indent copied one or more times according to the indentation level. In our example, we pretty-print JSON using four spaces for indentation.
If you need to convert a file containing Json text to a readable format, you need to convert that to an Object and implement toString() method(assuming converting to Java object) to print or write to another file in a much readabe format. You can use any Json API for this, for example Jackson JSON API.
MarshalIndent
will allow you to output your JSON with indentation and spacing. For example:
{
"data": 1234
}
The indent
argument specifies the series of characters to indent with. Thus, json.MarshalIndent(data, "", " ")
will pretty-print using four spaces for indentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With