To encode a struct to JSON string, there are three ways that provided by standard library :
- Using
Encoder
which convert struct to JSON string, then write it to io.Writer
. This one usually used if you want to send JSON data as HTTP request, or saving the JSON string to a file.
- Using
Marshal
which simply convert struct to bytes, which can be easily converted to string.
- Using
MarshalIndent
which works like Marshal
, except it's also prettify the output. This is what you want for your problem right now.
To compare between those three methods, you can use this code (Go Playground):
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type MainStructure struct {
Text string `json:"text,omitempty"`
Array []TestArray `json:"test_array,omitempty"`
}
type TestArray struct {
ArrayText string `json:"array_text,omitempty"`
}
func main() {
Test := MainStructure{
Text: "test",
Array: []TestArray{
{ArrayText: "test1"},
{ArrayText: "test2"},
},
}
// Using marshal indent
btResult, _ := json.MarshalIndent(&Test, "", " ")
fmt.Println("Using Marshal Indent:
" + string(btResult))
// Using marshal
btResult, _ = json.Marshal(&Test)
fmt.Println("
Using Marshal:
" + string(btResult))
// Using encoder
var buffer bytes.Buffer
json.NewEncoder(&buffer).Encode(&Test)
fmt.Println("
Using Encoder:
" + buffer.String())
}
The output will look like this :
Using Marshal Indent:
{
"text": "test",
"test_array": [
{
"array_text": "test1"
},
{
"array_text": "test2"
}
]
}
Using Marshal:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}
Using Encoder:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}