JSON Decode into Objects

· 172 words · 1 minute read

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.

 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
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. 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!