JSON Encode an Array of Objects

· 132 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.

package main

import (

type Page struct {
    Title    string
    Filename string
    Content  string

type Pages []Page

var pages = Pages{
        "First Page",
        "This is the 1st Page.",
        "Second Page",
        "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!