JSON Encode - Pretty Print

· 250 words · 2 minutes read

Is JSON for computers or humans to read? Well, hopefully with this snippet it can be for both. Instead of just dumping all the json in one line, we instead format it and indent it for readability purposes.

Using the MarshalIndent function in the json package we’re able to not only specify the data to encode, but also a prefix and an indentation string. In our example we’re not to worried about the prefix, but the indentation (3rd parameter) allows us to structure our code. We’re using 4 spaces for each indent level, but you can pick what ever suits you.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Game struct {
    Title       string   `json:"title"`
    Description string   `json:"description"`
    Platform    []string `json:"platform"`
}

func main() {

    myGame := Game{
        Title:       "Fifa 19",
        Description: "Football simulation game, based on UEFA players",
        Platform:    []string{"PS4"},
    }

    // For comparison, the usual way would be: j, err := json.Marshal(myGame)

    // MarshalIndent accepts:
    // 1) the data
    // 2) a prefix to place on all lines but 1st
    // 3) an indent to place before lines based on indent level

    // Print Json with indents, the pretty way:
    prettyJSON, err := json.MarshalIndent(myGame, "", "    ")
    if err != nil {
        log.Fatal("Failed to generate json", err)
    }
    fmt.Printf("%s\n", string(prettyJSON))
}

check is date set or not

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!