Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pretty-print JSON using Go?

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.

like image 416
Brad Peabody Avatar asked Oct 17 '22 18:10

Brad Peabody


People also ask

How do I print JSON pretty Golang?

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.

How do I make JSON data readable?

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.


1 Answers

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.

like image 453
Alexander Bauer Avatar answered Oct 20 '22 07:10

Alexander Bauer