JSON Encode an Array of Objects

· 169 words · 1 minute read

This is how to convert any object within go, into the JSON data structure. In our example we’re using an array of Page objects, each with their own properties and encoding them. We’re then just printing this string to Stdout, but if we were using the net/http to create an api, we would want to write to the http writer instead.

 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
37
package main

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

type Page struct {
    Title    string
    Filename string
    Content  string
}

type Pages []Page

var pages = Pages{
    Page{
        "First Page",
        "page1.txt",
        "This is the 1st Page.",
    },
    Page{
        "Second Page",
        "page2.txt",
        "The 2nd Page is this.",
    },
}

func main() {
    pagesJson, err := json.Marshal(pages)
    if err != nil {
        log.Fatal("Cannot encode to JSON ", err)
    }
    fmt.Fprintf(os.Stdout, "%s", pagesJson)
}

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!