Golang Code

JSON Decode into Objects

· 138 words · 1 minute read #api #decode #json #log #marshal #objects #pages #string #struct #unmarshal

This is a way of taking a JSON string and forming an object array with it. These objects can then be used and manipulated as you please. This uses the json encode as well just to demonstrate it works. The primary function used to process the json is the json.Unmarshal method.

package main

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

type Page struct {
    Title    string
    Filename string
    Content  string
}

type Pages []Page

var rawJson = []byte(`[{"Title":"First Page","Filename":"page1.txt","Content":"This is the 1st Page."},{"Title":"Second Page","Filename":"page2.txt","Content":"The 2nd Page is this."}]`)

func main() {
    // Decoding the JSON
    var pages Pages
    err := json.Unmarshal(rawJson, &pages)
    if err != nil {
        log.Fatal("Problem decoding JSON ", err)
    }

    // Re-encode for demonstration purposes
    rejson, err := json.Marshal(pages)
    if err != nil {
        log.Fatal("Cannot encode to JSON ", err)
    }
    fmt.Fprintf(os.Stdout, "%s", rejson)
}
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.

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!