0.00

JSON encode in Go Lang

Sample method and data structure to encode as JSON in go


programming language: go lang 1.11 or later
operating system: any
Updated:


Sample Data structure definition, with JSON fields mapping:

// data.go

package main

type MyDataStruct struct {
    Id     int64   `json:"id"`
    Type   uint64  `json:"type"`
    Name   string  `json:"name"`
    Value  float64 `json:"value"`
    Status bool    `json:"status"`
}


Method definition: JSON encode

// lib.go

package main

import (
    "bytes"
    "encoding/json"
)

func JsonEncode(data interface{}, prettyprint bool, htmlsafe bool) (s string, e error) {
    //-- no need any panic handler
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(htmlsafe)
    if(prettyprint == true) {
        encoder.SetIndent("", "    ") // 4 spaces
    } //end if
    //--
    err := encoder.Encode(data)
    if(err != nil) {
        return "", err
    } //end if
    //--
    return buffer.String(), nil
    //--
} //END FUNCTION


Sample usage

// app.go
// go build app.go lib.go data.go

package main

import (
    "log"
)

func main() {

    s := MyDataStruct{}
    s.Id = 1
    s.Type = 1001
    s.Name = "Sample"
    s.Value = 10.01
    s.Status = true

    json, err := JsonEncode(s, false, true)
    if(err != nil) {
        log.Fatal(err)
    }

    log.Println(json) // will output: {"id":1,"type":1001,"name":"Sample","value":10.01,"status":true}

}